import React from 'react';
class ComponentWithState extends React.Component {
constructor(props) {
super(props);
this.state = {
counter: 0,
name: '',
}
}
onButtonClicked() {
this.setState({
counter: this.state.counter + 1
})
}
render() {
return (
<div>
<button onClick={this.onButtonClicked}>Clicked {this.state.counter} times</button>
<h1>My name is {this.state.name}</h1>
<p>Fruit passed in as prop {this.props.fruit}</p>
</div>
)
}
}
export default ComponentWithState;
- Create function with the same name as class, and take props in as the only parameter
function ComponentWithState(props) {
}
- Copy return portion of the "render" function in the class into the body of the function
function ComponentWithState(props) {
return (
<div>
<button onClick={this.onButtonClicked}>Clicked {this.state.counter} times</button>
<h1>My name is {this.state.name}</h1>
<p>Fruit passed in as prop {this.props.fruit}</p>
</div>
)
}
- For every property inside the class constructor
this.state
, create an equivalent useState. Make sure anywhere that references e.g. this.state.counter
you swap out with the new state variable which is just counter
function ComponentWithState(props) {
const [counter, setCounter] = React.useState(0);
const [name, setName] = React.useState('');
return (
<div>
<button onClick={this.onButtonClicked}>Clicked {counter} times</button>
<h1>My name is {name}</h1>
<p>Fruit passed in as prop {this.props.fruit}</p>
</div>
)
}
- Find any instances of
this.props
and make it just props
function ComponentWithState(props) {
const [counter, setCounter] = React.useState(0);
const [name, setName] = React.useState('');
return (
<div>
<button onClick={this.onButtonClicked}>Clicked {counter} times</button>
<h1>My name is {name}</h1>
<p>Fruit passed in as prop {props.fruit}</p>
</div>
)
}
- Replace any event handlers (e.g. onChange or onClick) functions into functions defined inside our component. Also replace any instances of
this.setState({})
with the appropriate setX
variable we've created using useState
. Make sure to then update the onClick={this.onButtonClicked}
to just be onClick={onButtonClicked}
function ComponentWithState(props) {
const [counter, setCounter] = React.useState(0);
const [name, setName] = React.useState('');
function onButtonClicked() {
setCounter(counter + 1)
}
return (
<div>
<button onClick={onButtonClicked}>Clicked {counter} times</button>
<h1>My name is {name}</h1>
<p>Fruit passed in as prop {props.fruit}</p>
</div>
)
}