Skip to content

Instantly share code, notes, and snippets.

@david-crespo
Last active January 18, 2021 07:14
Show Gist options
  • Save david-crespo/6e5e82dc3709e2f8a780d043dd51aaac to your computer and use it in GitHub Desktop.
Save david-crespo/6e5e82dc3709e2f8a780d043dd51aaac to your computer and use it in GitHub Desktop.
React in 2 Minutes

React in 2 minutes

a React component takes

  • props, which are like HTML attributes, arguments passed in from outside

it has

  • state, an internal object to track state, e.g., the contents of a text field or the value of a checkbox
  • setState, call this to update the state object and trigger a re-render (never modify state directly)

and it has some lifecycle methods you can hook into by defining them

  • render (required), i.e., the template: based on props and state, what should my HTML look like?
  • componentDidMount, do something right when the component loads, like fetch some data
  • componentWillUnmount, do stuff right before getting removed from the page, like cancel outstanding requests

there are more things but they’re not important. here’s an example that shows all of that except componentDidMount and componentWillUnmount

class Toggle extends React.Component {
  state = { isToggleOn: true };  // initial state

  handleClick = () => this.setState({ isToggleOn: !this.state.isToggleOn });

  render() {
    return (
      <button onClick={this.handleClick}>
        {this.props.otherText}
        {this.state.isToggleOn ? 'ON' : 'OFF'}
      </button>
    );
  }
}

ReactDOM.render(
  <Toggle otherText="hello!" />,
  document.getElementById('root')
);

Function component

If you don't need any state and just want a basic template, you can define a function from props to JSX. Call it the same way as a component defined with class.

function Button(props) {
  return (
    <button onClick={props.onClick}>
      {props.text}
    </button>
  );
}

ReactDOM.render(
  <Button text="hello!" onClick={() => alert(1)} />,
  document.getElementById('root')
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment