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.

    javascript Copy
    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.

    javascript Copy
    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

middle

What is prop drilling and how can you avoid it?

senior

When shall we use useReducer hook in ReactJS?

junior

What are portals in React and when do we need them?

Bình luận

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

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