Home > Back-end >  Is there a way to access nested DOM Elements in React?
Is there a way to access nested DOM Elements in React?

Time:08-03

In my app, I have an input field and a ref that stores the value of the user input. I also have a bunch of React Links in a div that serve as recommended keywords for the user to search.

Is there a way for me to dynamically modify the React Link element that has the same text as the user input?

EG: user inputs "shoe" and there's a <Link to="/display?shoe"> Shoe </Link>, then I can get that element and add some inline css to it.

Snippet

CodePudding user response:

In React you can access the DOM element using Refs.

Creating Refs: create using React.createRef() and attach it to the React elements using ref attribute.

CodePudding user response:

This can be done if you store the user input in state. So whenever state changes the Link is updated

Example:

const [userInput, setUserInput] = useState(''); // store input value
<Link to=`/display?${userInput}`>{userInput}</Link>
  • Related