<main></main>
class Character extends React.Component {
constructor(props) {
super(props);
this.state = { data: {} };
this.activeRequest = null;
}
refreshData() {
if (this.activeRequest) {
this.activeRequest.abort();
}
this.activeRequest = $.get(`https://swapi.co/api/people/${this.props.id}`, (data) => {
this.setState({ data });
});
}
componentDidMount() {
this.refreshData();
}
componentDidUpdate(nextProps, nextState) {
if (nextProps.id !== this.props.id) {
this.refreshData();
}
}
render() {
return <p>I am a character with ID {this.props.id} and my name is {this.state.data.name}</p>
}
}
class App extends React.Component {
constructor(props) {
super(props);
this.state = { id: 1 };
this.shuffle = this.shuffle.bind(this);
}
shuffle() {
this.setState({ id: _.random(1, 10) });
}
render() {
return (
<div>
<p>Hello World</p>
<Character id={this.state.id} />
<button onClick={this.shuffle}>Shuffle</button>
</div>
);
}
}
ReactDOM.render(<App />, document.querySelector('main'));
View Compiled
This Pen doesn't use any external CSS resources.