coderz
coderz

Reputation: 4989

React JSX - dynamic html attribute

In JSX, we can indicate attribute value dynamically like:

<div className={this.state.className}>This is a div.</div>

Is it possible to indicate attribute (including attribute name and attribute value) dynamically? Like:

const value = emptyValue ? "" : "value='test'";
<input {value} />

That means, once emptyValue is true, "input" tag should not include "value" attribute (value="" is different from no value attribute, as one is show empty in input field, another is show existing text in input field).

Upvotes: 6

Views: 6237

Answers (2)

AlexeyKuznetsov
AlexeyKuznetsov

Reputation: 412

ES6 object expansion only works for objects. Therefore to generate a dynamic attribute, try something like this:

const value = emptyValue ? {} : { value: 'test' }
<a  {...value} ></a>

Note value will always be an object.

Upvotes: 6

Lojka
Lojka

Reputation: 167

you can insert whole element in if statement in render function, but before return like this:

render() {

var input = (<input />);
if (!emptyValue) {
    input = (<input value='test'/>)
}

return (
    <div>
        {input}
    </div>
    )
}

Upvotes: 1

Related Questions