5

I'm trying to get React to render an empty attribute, but instead it's not including it at all. Any ideas?

render(){
    return <myComponent foo="{ this.state.foo }" />
}

when this.state.foo if falsey, this yields:

<mycomponent />

whereas I want:

<myComponent foo />
1
  • @Alexander -- Thanks, but componentDidMount only runs once, and the general concept of manually setting attributes via DOM access is very anti-react :) Commented Feb 17, 2015 at 19:41

1 Answer 1

2

Your problem is not that the attribute value is blank; it's that your attribute is neither a native html spec element or prefaced with data. From the JSX Gotchas pages:

If you pass properties to native HTML elements that do not exist in the HTML specification, React will not render them. If you want to use a custom attribute, you should prefix it with data-.

You should do something like this:

render(){
    return <myComponent data-foo={ this.state.foo || '' } />
}

Update (as @alexander pointed out):

You also need to specify a backup empty string if data-foo can return null. I've updated my example

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

1 Comment

Sorry, it already is a data- attr (wasn't paying attention to that when writing the example code), still not showing up. jsfiddle.net/69z2wepo/2489

Your Answer

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