1

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" />
    }
2
  • 1
    React hooks don't change anything that would apply to the code you're showing. That code would look no different for a function component. Commented Mar 8, 2019 at 15:50
  • Can you explain your question a bit more? What you've done seems to already answer your question unless I'm not understanding you? Commented Mar 8, 2019 at 15:55

2 Answers 2

1

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} />
Sign up to request clarification or add additional context in comments.

1 Comment

Rather than creating a separate component I just created a const DirectionIcon = {the above conditional render} and in return wrote <DirectionIcon /> . As in your comment you defined myIComponent I think the first letter should be capital for react to recognize it as a React component. Apart form that all went good. Thanks.
0
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.

1 Comment

const myIComponent = ({sortDirection, iClassName}) => { return <i onclick={() => setSortDirection(sortDirection)} className={iClassName} /> }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.