I will, for this answer, assume you are rather asking about how to convert a class-based component to a functional component since there isn't anything really to convert to a custom react hook.
Steps to convert:
- Convert state to use the
useState
React hook.
- Replace references of
this.state.pollAnswers
to pollAnswers
.
- Replace references to
this.setState
to setPollAnswers
.
- Use proper functional state update to not mutate existing state.
- Replace reference of
this.handleVote
to handleVote
and declare const
.
Code
import React, { useState } from "react";
import Poll from "react-polls";
// Declaring poll question and answers
const pollQuestion = "Youtube is the best place to learn ?";
const answers = [ // <-- renamed to avoid collision with state variable
{ option: "Yes", votes: 7 },
{ option: "No", votes: 2 },
{ option: "don't know", votes: 1 }
];
const Fakepolls = () => {
// Setting answers to state to reload the component with each vote
const [pollAnswers, setPollAnswers] = useState([...answers]);
// Handling user vote
// Increments the votes count of answer when the user votes
const handleVote = (voteAnswer) => {
setPollAnswers((pollAnswers) =>
pollAnswers.map((answer) =>
answer.option === voteAnswer
? {
...answer,
votes: answer.votes + 1
}
: answer
)
);
};
return (
<div>
<Poll
question={pollQuestion}
answers={pollAnswers}
onVote={handleVote}
/>
</div>
);
};
export default Fakepolls;
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…