Reputation: 385
I am woking on a sample ReactJS application, where I want to pass a variable from one component to another.
class Layout extends React.Component{
constructor(props) {
super(props);
this.state = {keyword: ''};
}
render() {
return (
<div className="wrapper">
<Search />
<Listing />
</div>
);
}
};
ReactDOM.render(
<Layout />, app
);
In the above code, I want to pass a variable from <Search />
component to <Listing />
component.
Upvotes: 0
Views: 3288
Reputation: 7764
You can make it with function like
class Layout extends React.Component {
constructor(props) {
super(props);
this.state = {
keyword: '',
yourVariable: null
};
}
sendVariable(newValue) {
this.setState({ yourVariable: newValue });
}
render() {
return (
<div className="wrapper">
<Search onChange={this.sendVariable.bind(this)} />
<Listing sendValue={this.state.yourVariable} />
</div>
);
}
};
class Search extends React.Component{
render(){
let variable = "";
return <div onClick={this.porps.onChange(variable)}></div>;
}
}
Or use React-redux.
Upvotes: 1
Reputation: 1256
Rlijo you'd pass props to components as follows:
<Search paramA={someParam} paramB={anotherParam} />
and to use the props within the Search component you'd call this.props.paramA
(if using classes).
The way you've got the components setup, you wouldn't be able to share the state from the Search component (i.e. the object in this.state within Search) with the Listing component. There are libraries such as Redux designed to solve problems of shared state across components.
Props (or variables or params) flow downward so you'd need to provide shared props from a parent component. See you could provide this.state.keyword as a prop to both Search and Listing as these two components sit inside this parent component.
Upvotes: 1