In React, ref is typically used to access DOM nodes or create references to components. However, ref is not a standard property that can be directly passed to sibling components like props. Nevertheless, we can achieve this indirectly through several approaches. Here are several methods to pass ref to sibling components in React:
Method One: Using React.createRef() and Parent Component as Intermediary
We can create a ref in the parent component and pass it to child components via props. The key here is the parent component acting as an intermediary.
Example code:
jsximport React, { createRef, Component } from 'react'; class ParentComponent extends Component { nodeRef = createRef(); render() { return ( <div> <ChildA ref={this.nodeRef} /> <ChildB nodeRef={this.nodeRef} /> </div> ); } } const ChildA = React.forwardRef((props, ref) => ( <input ref={ref} /> )); function ChildB({ nodeRef }) { function handleClick() { if (nodeRef.current) { nodeRef.current.focus(); // Use the passed ref to call methods } } return <button onClick={handleClick}>Focus on input in ChildA</button>; }
In this example, the ChildA component receives the ref via React.forwardRef, while ChildB receives the same ref through props. Then ChildB can use this ref to manipulate the DOM elements of ChildA.
Method Two: Using Context API
If the project structure is complex or the component hierarchy is deep, you can use React's Context API to pass data across component hierarchies (including ref).
Example code:
jsximport React, { createContext, useRef, useContext } from 'react'; const RefContext = createContext(null); function ParentComponent() { const sharedRef = useRef(null); return ( <RefContext.Provider value={sharedRef}> <ChildA /> <ChildB /> </RefContext.Provider> ); } const ChildA = () => { const inputRef = useContext(RefContext); return <input ref={inputRef} />; }; function ChildB() { const inputRef = useContext(RefContext); function handleClick() { if (inputRef.current) { inputRef.current.focus(); } } return <button onClick={handleClick}>Focus on input in ChildA</button>; }
In this method, the ref is stored in the Context and passed down through the Provider. This allows any consumer component to access and interact with this ref.
Summary
Although React does not allow directly passing ref as props to sibling components, we can indirectly achieve this by utilizing the parent component as an intermediary or using the Context API. Both methods can be chosen based on specific application scenarios and requirements.