user3284707
user3284707

Reputation: 3341

ReactJS Context - conditional inside consumer

Using ReactJs context, I have a count value which I am displaying in my Nav bar. I don't want this to shown when the value is 0, however I cannot work out how to achieve this.

Basically inside the CounterContext.Consumer I would like to add an if statement to only display if the counter > 0

Here is my code snippet

<NavLink to={"/counterList"} className="nav-link" activeClassName="active">
    <span className="glyphicon glyphicon-education" /> Counter List
    <CounterContext.Consumer>
        {(c) =>
            <span className="badge badge-danger ml-10">{c.counters.filter(x => x.count > 0).length}</span>
        }
    </CounterContext.Consumer>
</NavLink>

Upvotes: 1

Views: 660

Answers (1)

Tholle
Tholle

Reputation: 112807

You could give the arrow function a body {}, store the value in a variable, and return null if it is equal to 0.

Example

<NavLink to={"/counterList"} className="nav-link" activeClassName="active">
  <span className="glyphicon glyphicon-education" /> Counter List
  <CounterContext.Consumer>
    {c => {
      const count = c.counters.filter(x => x.count > 0).length;

      return count !== 0 ? (
        <span className="badge badge-danger ml-10">{count}</span>
      ) : null;
    }}
  </CounterContext.Consumer>
</NavLink>

Upvotes: 2

Related Questions