rockfight
rockfight

Reputation: 1996

How to render if..else if...else type in React functional component?

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

Answers (2)

Avick Mukherjee
Avick Mukherjee

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

victor zadorozhnyy
victor zadorozhnyy

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

Related Questions