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 checkboxsetState
, call this to update the state object and trigger a re-render (never modifystate
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 datacomponentWillUnmount
, 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')
);
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')
);