Câu hỏi phỏng vấn Reactjs
Câu hỏi

How would you pass data from child to parent component in React?

Câu trả lời

To pass data from a child component to a parent component in React, you typically use a callback function approach. Here's a step-by-step explanation of how this can be implemented:

  1. Define a Callback Function in the Parent Component: Start by creating a function in the parent component that is designed to handle the data coming from the child component. This function will typically update the state of the parent component based on the data received.

    function ParentComponent() {
        const [data, setData] = useState('');
    
        const handleDataFromChild = (childData) => {
            setData(childData);
        };
    
        return (
            <div>
                <ChildComponent sendDataToParent={handleDataFromChild} />
                <p>Data from child: {data}</p>
            </div>
        );
    }
  2. Pass the Callback Function as a Prop to the Child Component: The next step is to pass this callback function as a prop to the child component. This allows the child component to call this function and send data back to the parent.

    function ChildComponent({ sendDataToParent }) {
        const someData = "Data from Child";
        return (
            <button onClick={() => sendDataToParent(someData)}>Send Data to Parent</button>
        );
    }
  3. Invoke the Callback Function from the Child Component: Within the child component, you can invoke the passed call...

middle

middle

Gợi ý câu hỏi phỏng vấn

junior

How to call loading function with React useEffect only once?

middle

What is the difference between HTML and React event handling?

middle

What's the typical pattern for rendering a list of components from an array in React?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào