ReactJS Two components communicating, in angular, we are simply using service best way, but here I am new in react 16.
Two components in react can communicate in following ways
Parent -> Child Component via props
Child -> Parent via callback
Child -> Child via using their closet parent component
eg:
import React, {Component} from 'react';
class Parent extends Component {
constructor() {
super()
this.state = {
name: "John Doe"
}
this.changeName = this.changeName.bind(this)
}
changeName(newName) {
this.setState({
name: newName
})
}
render() {
return (
<div>
// passing data from parent component to child component using props
// name={this.state.name} changeName={this.changeName}
<Child name={this.state.name} changeName={this.changeName} />
<SecondChild name={this.state.name} />
</div>
)
}
}
function Child(props) {
return (
<div>
<h1>My name in Child Component is: {props.name} </h1>
// passing data from child component to parent component using Callback
// onClick={() => props.changeName('Jeremy Smith')}
<button onClick={() => props.changeName('Jeremy Smith')}>Change Name</button>
// when button is clicked "Jeremy Smith" is passed to parent component and
// from their passed to both Child and SecondChild components
// this way we communicate between two child components
</div>
)
}
function SecondChild(props) {
return <h1>My Name in Second Child Component is: {props.name}</h1>
}
In addition
You can also use React Context API for passing data down to Child Components.
Or use state management library like redux for creating single shared store and pass required data to components.