Kyle
Kyle

Reputation: 4298

Conditionally set checkbox state based on variable in ReactJS

class Example extends React.Component {
  constructor() {
    super();
    this.isChecked = this.isChecked.bind(this);
  }

  isChecked(ex){
    return this.props.defaults && $.inArray(ex, this.props.defaults);
  }

  render() {
    return (
      <div className="example">
        {this.props.items.map(item => (
          var checked = this.isChecked({item.type});

          <span key={item.type}>
            <input type="checkbox" {checked ? 'checked' : ''} name="example" value={item.type} id={item.type} />
            <label htmlFor={item.type}>{item.display}</label>
          </span>
        ))}
      </div>
    );
  }
}

In the above example, I have passed a list of items to the component this.props.items and a list of defaults this.props.defaults. For each item, if the item is in the list of defaults, I would like its state to be checked. Leaving the overall design the same, how can I do that? (Note: I realize I can redesign the application to avoid the issue of declaring the variable inside the map. That is not the question).

The above code doesn't work (obviously), I am just trying to give everyone an idea of what I'm attempting here. The error given if you run this is something like "unexpected token" at the spot where "var" is declared.

Upvotes: 3

Views: 13497

Answers (1)

Drew Schuster
Drew Schuster

Reputation: 2691

the render method had some syntax errors, this should work:

render() {

  return (
    <div className="example">
      {this.props.items.map((item) => {
        var checked = this.isChecked(item.type);

        return (
          <span key={item.type}>
            <input type="checkbox" checked={checked ? 'checked' : ''} name="example" value={item.type} id={item.type} />
            <label htmlFor={item.type}>{item.display}</label>
          </span>
        )
      })}
    </div>
  );
}

That main mistakes were declaring the function in map, you have to wrap item in parens and surround the function with brackets instead of parens. If a fat arrow function has only one statement, you don't need to specify return. But in this case you added the var checked line, so you now have to explicitly make the other line a return statement. There was also an issue with how you set checked in the input. Hope that helps!

Upvotes: 11

Related Questions