3

I have a Todo component. My ToDoContainer downloads all the todos using fetch. The response looks like the following:

[
    { id: 0, checked: 1, text: "bla bla" },
    { id: 1, checked: 0, text: "bla bla 2" }
]

After successfully getting my todos, I'm passing them down from TodoContainer to Todo component which renders them.

Unfortunately I can't make it work:

<li>
    <input type="checkbox" />
    { this.props.text }
</li>

How do I pass the info about the checkbox being checked or not?

I've tried:

<li>
    <input type="checkbox" {this.props.checked ? 'not', 'working') />
    { this.props.text }
</li>

But it looks like you can't use {} within tags in JSX?

The official guide isn't helpful either, because doing something like:

render() {
    let todoInput = null;
    if (this.props.checked) {
        todoInput = '<input type="checkbox" checked />';
    }
    else {
        todoInput = '<input type="checkbox"/>';
    }

    return (
        <li>
            { todoInput } { this.props.text }
        </li>
    );
}

Won't work as it just renders the HTML (not the input itself) and I do not want to create new component just for that or to dangerously set HTML.

Any hints? :(

5

1 Answer 1

3

You can use :

<input type="checkbox" checked={this.props.checked} />

OR

Remove single quotes

From :

todoInput = '<input type="checkbox" checked />';

Like this :

todoInput = <input type="checkbox" checked />;

OR

Conditional tags :

this.props.checked ? <CompA /> : <CompB />;
Sign up to request clarification or add additional context in comments.

4 Comments

Wow, thanks, but can't I do it any other way? Like IF in jsx itself? Instead of foo ? 'bar' : 'bar2' we have there like extra 5 lines of code. In HTML checked=1 & checked=0 and checked=anything is always checked AFAIK.
Yes you can just remove single quotes if its element and it will work.
unfortunately it does not work as expected. Once I set 'checked' I can never uncheck the input. onChange handlers doesn't work as well.
@VivekDoshi it was an example i put together. hope it help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.