pass state from child to parent react functional component code example
Example 1: pass setstate to child
class ChildExt extends React.Component {
render() {
return (<div><button onClick={() => this.props.handleForUpdate('someNewVar')}>Push me</button></div>
)}
}
class ParentExt extends React.Component {
constructor(props){
super(props);
this.state = {lol: false }
}
handleForUpdate(someArg){
this.setState({lol: true});
console.log(someArg);
}
render() {
return (<ChildExt handleForUpdate={this.handleForUpdate.bind(this)} />)
}
}
Example 2: pass state to child react
class SomeParentComponent extends React.Component {
constructor(props) {
super(props);
this.state = {color: 'red'};
}
render() {
return <SomeChildComponent color={this.state.color} />;
}
}
Example 3: 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}/>
</div>
);
}
export default App;
function Todo(props) {
return (
<div>
{props.todos.map(todo => {
return (
<h1>{todo.title}</h1>
)
})}
</div>
);
}