How do I pass the reft from the parent component to the child component in React?
- User
How do I pass the reft from the parent component to the child component in React?
- Assistant
In React, you can pass props from a parent component to a child component by simply declaring the prop in the parent component and passing it as an attribute to the child component when rendering it.
Here is an example of how to pass a prop called
datafrom a parent component to a child component:ParentComponent.js:
import React from 'react'; import ChildComponent from './ChildComponent'; const ParentComponent = () => { const data = 'Hello from Parent'; return ( <ChildComponent data={data} /> ); }; export default ParentComponent;ChildComponent.js:
import React from 'react'; const ChildComponent = (props) => { return ( <div> <p>{props.data}</p> </div> ); }; export default ChildComponent;In this example, the
dataprop is passed from theParentComponentto theChildComponentby setting it as an attribute with the same name when rendering theChildComponentin theParentComponent. TheChildComponentthen receives the prop in its function arguments and can access it usingprops.datawithin the component. - User
I meant ref
- Assistant
To pass a ref from a parent component to a child component in React, you can create a ref in the parent component and pass that ref as a prop to the child component. Here is an example:
ParentComponent.js:
import React, { useRef } from 'react'; import ChildComponent from './ChildComponent'; const ParentComponent = () => { const childRef = useRef(null); return ( <ChildComponent forwardedRef={childRef} /> ); }; export default ParentComponent;ChildComponent.js:
import React, { useEffect } from 'react'; const ChildComponent = ({ forwardedRef }) => { useEffect(() => { if(forwardedRef.current) { forwardedRef.current.focus(); } }, []); return ( <input ref={forwardedRef} /> ); }; export default ChildComponent;In this example, the
ParentComponentcreates a ref using theuseRefhook and passes it to theChildComponentas a prop calledforwardedRef. TheChildComponentuses this forwarded ref to assign it to an input element using therefattribute. TheuseEffecthook in theChildComponentis used to focus on the input element when the component mounts.