Skip to content

Instantly share code, notes, and snippets.

@fxfactorial
Last active March 25, 2017 18:49
Show Gist options
  • Save fxfactorial/031a58a545efafac92781d43349f61d6 to your computer and use it in GitHub Desktop.
Save fxfactorial/031a58a545efafac92781d43349f61d6 to your computer and use it in GitHub Desktop.
Communicating between components
import React, {Component} from 'react';
import { render } from 'react-dom';
class TopBox extends Component {
render () {
const s = {backgroundColor:'red'};
const all_names = this.props.all_names.map(n => {
return (
<p>{n}</p>
);
});
return (
<div style={s}>
{all_names}
</div>
);
}
}
class BottomBox extends Component {
constructor() {
super();
this.handler = this.handler.bind(this);
}
handler() {
this.props.some_function(''+Math.random());
}
render () {
const s = {backgroundColor:'orange'};
return (
<div style={s}
onClick={this.handler}
>
Click me
</div>
);
}
}
class Application extends Component {
constructor() {
super();
this.state = {all_names: ['hello']};
this.add_name = this.add_name.bind(this);
}
add_name(item) {
this.setState({
all_names:[...this.state.all_names, item]
});
}
render() {
return (
<div>
<TopBox
all_names={this.state.all_names}
/>
<BottomBox
some_function={this.add_name}
/>
</div>
);
}
};
render(<Application/>,
document.getElementById('container'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment