O. Altun
O. Altun

Reputation: 725

How to make the existance of an html attribute dynamic?

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>
    );
  }
}

Upvotes: 1

Views: 67

Answers (1)

Amit Chauhan
Amit Chauhan

Reputation: 6919

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>
    );
  }
}

Upvotes: 2

Related Questions