1

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
  • 1
    Well, you could always put a wrapper around it and hack the DOM yourself in a useLayoutEffect, or if it's an npm package, patch-package. Commented May 27, 2020 at 16:08

1 Answer 1

2

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>
  )
}
Sign up to request clarification or add additional context in comments.

2 Comments

Why myRef.current equals null?
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.