Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React - JSX conditional tags

Tags:

reactjs

jsx

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? :(

like image 203
Wordpressor Avatar asked Jul 31 '26 09:07

Wordpressor


1 Answers

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 />;
like image 86
Vivek Doshi Avatar answered Aug 03 '26 01:08

Vivek Doshi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!