• Home
  • How to select sibling element with react?

How to select sibling element with react?

To select a sibling element with React, you can use the ref attribute to create a reference to the element, and then use the current property of the ref to access the element. Here is an example:

import React, { useRef } from 'react';

function Example() {
const firstInput = useRef(null);
const secondInput = useRef(null);

function focusSecondInput() {
firstInput.current.focus();
secondInput.current.focus();
}

return (
<>
<input ref={firstInput} />
<input ref={secondInput} />
<button onClick={focusSecondInput}>Focus Second Input</button>
</>
);
}

In this example, we have two input elements and a button. The button has an onClick handler that focuses on the first input and then the second input when clicked. The refs for the two input elements are created using the useRef hook, and the current property of each ref is used to access the input elements.