N
N
nivaech2019-05-24 02:29:07
JavaScript
nivaech, 2019-05-24 02:29:07

Why doesn't condition work in JSX?

There is a function that, depending on the condition, renders a certain array of colors, depending on the selected category. The conditions are simple - if such and such props === true, then the function should work and display the required set. But doesn't work.
Here is the function:

displayColors = (colorSet) => {
 colorSet.map((color, index) => {
    return (
<li className={"filter-item " + (this.state.color === color ? "active-item" : null)} key={index}
onClick={() => this.handleFilter("color", color)}> {color} </li>
            )
          })
    }

The same function calls the handleFilter function, which takes the required value, changes the state, and displays the required category.
handleFilter = (name, value) => {
    this.setState ({
        [name]: value
    }, this.sortData)
}

And this is what the condition looks like:
<ul className = {"filter-list colors-list " + (colorFilter ? "color-container-visible" : null)}>
    {(categoryOneColors ? displayColors(colorSet) : null )}
    {(categoryTwoColors ? displayColors(colorSet2) : null )}
    ...
    ...
</ul>

The output is empty, but if you hardcode the condition manually, without a function, then everything works fine. What is the problem?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
ivanoffdan, 2019-05-24
@nivaech

 The problem is that displayColors does not return the generated array. It should be like this:

displayColors = (colorSet) => {
    return colorSet.map((color, index) => (
      <li
        className={`filter-item ${this.state.color === color ? 'active-item' : null}`}
        key={index}
        onClick={() => this.handleFilter('color', color)}
      > {color} </li>
    ));
  }

or so
displayColors = (colorSet) => colorSet.map((color, index) => (
    <li
      className={`filter-item ${this.state.color === color ? 'active-item' : null}`}
      key={index}
      onClick={() => this.handleFilter('color', color)}
    > {color} </li>
  ))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question