Reputation: 1996
I am using React hooks and following is the conditional rendering which I want to achieve where sortDirection
is a state. I want to render one of the <i>
tag based on sortDirection
. How can I achieve this ?
if (sortDirection == "ascending") {
return <i onclick={() => setSortDirection('descending')} className="fa fa-arrow-down" />
} else if (sortDirection == "descending") {
return <i onClick={() => setSortDirection('random')} className="fa fa-arrow-up" />
} else {
return <i onClick={() => setSortDirection('ascending')} className="fa fa-arrow-h" />
}
Upvotes: 1
Views: 3489
Reputation: 33
const MyIComponent = ({sortDirection, iClassName}) => {
return <i onclick={() => setSortDirection(sortDirection)} className={iClassName} />
}
You can pass sortDirection
and iClassName
dynamically from main component as a props then if conditions also you can avoid.
Upvotes: 0
Reputation: 969
You can just create a separate functional component and having the condition as a prop
const MyIComponent = (sortDirection) => {
if (sortDirection == "ascending") {
return <i onclick={() => setSortDirection('descending')} className="fa fa-arrow-down" />
} else if (sortDirection == "descending") {
return <i onClick={() => setSortDirection('random')} className="fa fa-arrow-up" /> }
return <i onClick={() => setSortDirection('ascending')} className="fa fa-arrow-h" />
}
const MainComponent = () => <myIComponent sortDirection={sortDirection} />
Upvotes: 1