Most  asked question "Pass data from Child to Parent" with multiple examples....

Most asked question "Pass data from Child to Parent" with multiple examples....

"State lifting" is a concept of React, State lifting refers to the practice of moving the state of a component higher up in the component tree, making it accessible to multiple child components. This is typically done to share state and synchronize the behavior of those child components.

State lifting is often used to:

  1. Share State: When you have multiple components that need access to the same piece of state data, you can lift that state up to a common ancestor component, making it accessible to all child components.

  2. Synchronize State: By lifting state up, you ensure that all child components receive the same state information. When a change occurs, all child components can reflect that change.

  3. Reduce Redundancy: Lifting state can help avoid the duplication of state management logic in multiple components, making your code more efficient and easier to maintain.

For example,

  1. Parent Component
import React, { useState } from 'react';
import { render } from 'react-dom';
import Child from './Child';

function Parent() {
  const [dataFromChild, setDataFromChild] = useState('Hello from Parent');

  const handleDataFromChild = (data) => {
    setDataFromChild(data);
  };

  return (
    <div>
         <Child value={dataFromChild} passData={handleDataFromChild} />
    </div>
  );
}

render(<Parent />, document.getElementById('root'));

Child Component

import React from 'react';

const Child = (props) => {
const dataPass = () => {
const data = "Data from child component"; 
// This can be any data you want to pass
    props.passData(data);
  };

  return (
    <div>
      <p>{props.value}</p>
      <button onClick={dataPass}>Pass data</button>
    </div>
  );
};

export default Child;
  1. Parent Component
import React from 'react';
import { render } from 'react-dom';
import Child from './Child';

function App() {
  const handleDataFromChild = (data) => {
    console.log(data);
  };

  return (
    <div>
      <Child passData={handleDataFromChild} />
    </div>
  );
}

render(<App />, document.getElementById('root'));

Child Component

import React, { useState } from 'react';

const Child = (props) => {
  const [text, setText] = useState('');

  const handleChange = (e) => {
    setText(e.target.value);
  };
  const handleSubmit = (e) => {
    props.passData(text);
    e.preventDefault();
  };
  return (
    <div>
      <form onSubmit={handleSubmit}>
        <input type="text" value={text} onChange={handleChange} />
        <button>Pass Data</button>
      </form>
    </div>
  );
};

export default Child;
  1. Imagine you have a simple React application for a ToDo list where you want to add items to the list from a child component and display them in the parent component.

    Parent Component

     import React, { useState } from 'react';
     import { render } from 'react-dom';
     import Child from './Child';
    
     function App() {
       const [todos, setTodos] = useState([]);
    
       const handleAddTodo = (todo) => {
         setTodos([...todos, todo]);
       };
    
       return (
         <div>
           <h1>Todo List</h1>
           <Child onAdd={handleAddTodo} />
           <ul>
             {todos.map((todo, index) => (
               <li key={index}>{todo}</li>
             ))}
           </ul>
         </div>
       );
     }
    
     export default App;
    
     render(<App />, document.getElementById('root'));
    

    Child Component

import React, { useState } from 'react';

function Child(props) {
  const [todo, setTodo] = useState('');

  const handleInputChange = (e) => {
    setTodo(e.target.value);
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    props.onAdd(todo); // Pass the to-do item to the parent component
    setTodo(''); // Clear the input field
  };

  return (
    <div>
      <form onSubmit={handleSubmit}>
        <input
          type="text"
          placeholder="Add a to-do"
          value={todo}
          onChange={handleInputChange}
        />
        <button type="submit">Add</button>
      </form>
    </div>
  );
}

export default Child;
  1. Shopping Card Application with basic functionality

    Parent Component

import React, { useState } from 'react';
import { render } from 'react-dom';
import Child from './Child';


function App() {
  const [cart, setCart] = useState([]);

  const handleAddToCart = (item) => {
    setCart([...cart, item]);
  };

  const calculateTotal = () => {
    return cart.reduce((total, item) => total + item.price, 0);
  };

  return (
    <div>
      <h1>Shopping Cart</h1>
      <div>
        <p>Total: ${calculateTotal()}</p>
      </div>
      <ul>
        {cart.map((item, index) => (
          <li key={index}>
            {item.name} - ${item.price}
          </li>
        ))}
      </ul>
      <Child id="1" name="Product A" price={10} onAddToCart={handleAddToCart} />
      <Child id="2" name="Product B" price={15} onAddToCart={handleAddToCart} />
    </div>
  );
}


render(<App />, document.getElementById('root'));

Child Component

import React from 'react';

function Child(props) {
  const handleAddToCart = () => {
    const newItem = {
      id: props.id,
      name: props.name,
      price: props.price,
    };
    props.onAddToCart(newItem); 
// Pass the item data to the parent component
  };

  return <button onClick={handleAddToCart}>Add to Cart</button>;
}

export default Child;

These are examples of how you can pass data from a child to a parent component in a real-world scenario.

Did you find this article valuable?

Support Sumit Singh by becoming a sponsor. Any amount is appreciated!