<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

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

  1. https://cdnjs.cloudflare.com/ajax/libs/react/16.2.0/umd/react.development.js
  2. https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.2.0/umd/react-dom.development.js
  3. https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js
  4. https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js