Redux is great, but we must also know the basics before using any framework or library, right? Thats what I did before learning bootstrap and doing the same with Redux and ReactJs. So, this article is all about establishing the basic communication channel b/w siblings using just ReactJs.
Let’s discuss the Requirement, My app has a child component which has to communicate with its sibling component. So it must happen through Parent with a Callback method from parent to child1 which will get the value from child1 and will pass it to the other child as props.
Simple, isn’t it?
Data Flow
Flow
Req: Child1 has an input field, on typing that value must be sent to child2 component via Parent
Parent Component
First, define a Callback function in Parent and send it as props to Child1
constructor(){ super(); this.state= { data : "" } }
formChild1(params) { this.setState({ data : params }) }
I have set a state variable data and updating its value using the callback function fromChild1 and sending the state value to Child2. Why using state? Because props are Immutable and it is always better to pass state as props. And if you want to pass static data always use props. Use state to pass dynamic data.
render() { return( \<div\> \<p\>Parent\</p\> \<Child callback={this.formChild1.bind(this)} /\> \<Child2 data={this.state.data} /\> \</div\> ); }
Child-1
Install prop-types because React.PropTypes is deprecated and React suggests you to use prop-types . Learn more
npm install prop-types
Import prop-types into child1
import PropTypes from 'prop-types';
define the child component
class Child1 extends Component {
getContent(event) { this.props.callback(event.target.value); }
render() { return ( \<div\> \<p\>Child One\</p\> \<input type="text" onChange={this.getContent.bind(this)} placeholder="Type Something in Child One"/\> \</div\> ); } }
getContent gets the input value onChange and will send it to parent through a call back function.
Define prop-types for Child1 :
Child1.protoTypes = { callback : PropTypes.func, }
We are type checking for the call back function.
Child-2
Define a simple component which renders <p> tag with the props value sent to it from parent.
class Child2 extends Component {
render() { return( \<p\>Child2 : {this.props.data}\</p\> ); }
}
That’s it. We have Now established a communication channel between sibling to sibling. And don’t forget to export the child components if you have separate files for parent, child1 and child2.
For reference see the code
And Finally,
Thanks for reading my post. I’d like to hear your thoughts in comments. If you like the article, please click the💚 below so that more people may read it.
Top comments (0)