- (In src/components) Create a new file called
LikeButton.js
- Import some really basic stuff here
- Import React itself, and Component and PropTypes
- What is Import?
- Export your like button class as the default and extend Component
- Add a
render
function
- You will need a div to show the number of likes. Add a static number of likes for now as seen in the below code snippet.
- You will need a button to enable liking the todo. Use your favorite emoji as the text.
<div className="like">
<div className="numLikes">
9
</div>
<button className="likeTodo">👍</button>
</div>
- Import
LikeButton
at the top of theTodoItem
component. - Insert your like button before the destroy button.
<LikeButton />
- Save your files and check it out in the browser.
Now we’ll make the number of likes pull from an initial state, at the end the number of likes.
- (In TodoItem.js) Add an initial state for
numLikes
of0
to thestate
class initializer property
state = {
numLikes: 0,
editing: false
}
- Now let’s pass
this.state.numLikes
andtodo.id
as props intoLikeButton
namednumLikes
andid
respectively.
<LikeButton numLikes={this.state.numLikes} id={todo.id} />
- (In LikeButton.js) Use an expression to show
numLikes
. Replace the number9
with:
{this.props.numLikes}
- Save the file and check out your browser. You should see a
0
next to the like button.
- At this point we could pass anything into numLikes. A string, a number, even an array. To protect from incorrect props being passed, React provides the concept of propTypes. PropTypes allows a component to declare the expected types for each prop, throwing an helpful error if an unexpected type is received.
- (In TodoItem.js) Change the
numLikes
prop in theLikeButton
element to a string like“five”
.
<LikeButton numLikes={“five”} id={todo.id} />
- Save the file, open the browser. You should see
“five”
next to each like button. That’s not good! - (In LikeButton.js) Create a static class object called
propTypes
and setnumLikes
andid
as numbers that are required.
static propTypes = {
numLikes: PropTypes.number.isRequired
}
- Save the file, open the browser with the developer console open. You should see a warning like this:
- (In TodoItem.js) Set the numLikes prop back to passing the state.
<LikeButton numLikes={this.state.numLikes} id={todo.id} />
- Save the file, open the browser and see a
0
next to the like button.
- 🥉 BRONZE: Use object destructuring in the like button component to destructure the
numLikes
prop. - 🥈 SILVER: Write an onClick handler on the
likeTodo
button that shows an alert with the todoid
. - 🏅 GOLD: This component has no lifecycle methods like
shouldComponentUpdate
, orcomponentDidMount
. Because of this, it does not need to extend Component. It can simply be a function that returns JSX. MakeLikeButton
an arrow function that receives the props as destructured parameters and returns JSX. Assign thepropTypes
to the function and export it.