1

In the following code, I want to make the "checked" attribute of the input dynamic. Obviously completed is a boolean. The compilation fails right at the start of {check} with the error TS1005: '...' expected.

import React from 'react';

export class TodoListItem extends React.Component<any, any> {
  render() {
    const {label, completed} = this.props;
    const check = completed? "checked": " ";
    return (
      <li className="todo">
        <label>
          <input type="checkbox"  {check}/> {label}
        </label>
      </li>
    );
  }
}
Emile Bergeron
  • 16,148
  • 4
  • 74
  • 121
Zargo
  • 625
  • 5
  • 17
  • 1
    Possible duplicate of [How to conditionally add attributes to React components?](https://stackoverflow.com/questions/31163693/how-to-conditionally-add-attributes-to-react-components) – JJJ Jul 18 '19 at 13:05

1 Answers1

2

You can directly pass checked={completed} so if completed is true checkbox will be checked otherwise unchecked.

import React from 'react';

export class TodoListItem extends React.Component<any, any> {
  render() {
    const {label, completed} = this.props;
    return (
      <li className="todo">
        <label>
          <input type="checkbox"  checked={completed} /> {label}
        </label>
      </li>
    );
  }
}
Amit Chauhan
  • 5,029
  • 1
  • 19
  • 34