pass props from child to parent react hooks code example

Example 1: pass props from parent to child react functional component

import React, { useState } from 'react';
import './App.css';
import Todo from './components/Todo'



function App() {
    const [todos, setTodos] = useState([
        {
          id: 1,
          title: 'This is first list'
        },
        {
          id: 2,
          title: 'This is second list'
        },
        {
          id: 3,
          title: 'This is third list'
        },
    ]);

return (
        <div className="App">
            <h1></h1>
            <Todo todos={todos}/> //This is how i'm passing props in parent component
        </div>
    );
}

export default App;


function Todo(props) {
    return (
        <div>
            {props.todos.map(todo => { // using props in child component and looping
                return (
                    <h1>{todo.title}</h1>
                )
            })}
        </div>  
    );
}

Example 2: React hooks update parent state from child

const EnhancedTable = ({ parentCallback }) => {
    const [count, setCount] = useState(0);
    
    return (
        <button onClick={() => {
            const newValue = count + 1;
            setCount(newValue);
            parentCallback(newValue);
        }}>
             Click me {count}
        </button>
    )
};

class PageComponent extends React.Component { 
    callback = (count) => {
        // do something with value in parent component, like save to state
    }

    render() {
        return (
            <div className="App">
                <EnhancedTable parentCallback={this.callback} />         
                <h2>count 0</h2>
                (count should be updated from child)
            </div>
        )
    }
}