Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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).

like image 558
coderz Avatar asked Mar 28 '17 20:03

coderz


2 Answers

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.

like image 76
AlexeyKuznetsov Avatar answered Sep 28 '22 05:09

AlexeyKuznetsov


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>
    )
}
like image 35
Lojka Avatar answered Sep 28 '22 06:09

Lojka