6

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

4
  • Why not <input value={emptyValue ? "" : "test"}>? Commented Mar 28, 2017 at 20:26
  • @AndrewLi you are correct. While I want once emptyValue is true, "value" attribute should not exist in the "input". Commented Mar 28, 2017 at 20:30
  • 1
    You could of course make it an object like: const props = { value: "test", otherProp: "blah" } and then <input {...props}> Commented Mar 28, 2017 at 21:49
  • 2
    value={emptyValue ? null : "test"} Commented Apr 8, 2018 at 12:39

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

2 Comments

But it's a string, not an object.
let obj = {}; if(emptyValue) { obj.value = "test" } <a {...obj} ></a> That is what I am talking about
1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.