Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
192
rated 0 times [  195] [ 3]  / answers: 1 / hits: 22997  / 6 Years ago, fri, november 16, 2018, 12:00:00

I'm mainly using Vue, and just recently picked up React. Loving it so far, and its quite similar in a lot of ways to Vue, which makes learning it way easier.



Now, let's consider two siblings component. I want to trigger something in component number one, when something happens in component number two. In Vue you can just bind window.bus = new Vue, and then emit in one of the components bus.$emit('event') and bind in the mounted() of the second component bus.$on('event', this.doSth).



How can you achieve that in React?


More From » reactjs

 Answers
6

A parent component can manage the state and methods consumed by child components when passed down through props.



The following example increments a count. SibOne displays the count and a button in SibTwo increments the count.



class App extends Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
incrementCount = () => {
this.setState({
count: this.state.count + 1
});
}
render() {
return (
<div className=App>
<SibOne count={this.state.count}/>
<SibTwo incrementCount={this.incrementCount}/>
</div>
);
}
}

const SibOne = props => <div>Count: {props.count}</div>;

const SibTwo = props => (
<button onClick={props.incrementCount}>
Increment Count
</button>
);


Demo: https://codesandbox.io/s/zqp9wj2n63



More on Components and Props: https://reactjs.org/docs/components-and-props.html


[#53106] Sunday, November 11, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
anders

Total Points: 295
Total Questions: 106
Total Answers: 104

Location: Angola
Member since Wed, Apr 13, 2022
2 Years ago
;