Suppose I have a React component without the capability of changing its source code. This component, lets say <Demo /> renders a lot of <a> ...<a/> HTML elements. Is it possible to add an attribute inside those elements programmatically and how?
1 Answer
you could use a wrapper where you create a reference for the wrapper tag. with that you could query for specific elements and change its attributes accordingly:
const wrapperComponent = props => {
const myRef = React.createRef()
useEffect(() => {
myRef.current.querySelector("a").innerText = "got changed!"
}, [myRef])
return (
<div ref={myRef}>
<Component {...props} />
</div>
)
}
2 Comments
Unknown developer
Why
myRef.current equals null?Rafael Buzatto de Campos
My guess is that you added the
ref to the Component directly instead of a wrapping tag, and if that's the case is not going to work.
useLayoutEffect, or if it's an npm package,patch-package.