how to pass value to child component in react code example
Example 1: pass data from child component to parent component react native
class Parent extends React.Component {
state = { message: "" }
callbackFunction = (childData) => {
this.setState({message: childData})
},
render() {
return (
<div>
<Child1 parentCallback = {this.callbackFunction}/>
<p> {this.state.message} </p>
</div>
);
}
}
class Child1 extends React.Component{
sendData = () => {
this.props.parentCallback("Hey Popsie, How’s it going?");
},
render() {
}
};
Example 2: pass element from child to parent react
Parent:
<div className="col-sm-9">
<SelectLanguage onSelectLanguage={this.handleLanguage} />
</div>
Child:
handleLangChange = () => {
var lang = this.dropdown.value;
this.props.onSelectLanguage(lang);
}
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>
);
}
Example 4: how to pass state from parent to child in react
class SomeParentComponent extends React.Component {
constructor(props) {
super(props);
this.state = {color: 'red'};
}
render() {
return <SomeChildComponent color={this.state.color} />;
}
}