I'd like to render an HTML5 attribute of a <select>
input so that I can use jquery image picker with react. My code is:
var Book = React.createClass({ render: function() { return ( <option data-img-src="{this.props.imageUrl}" value="1">{this.props.title}</option>
The issue is that even though {this.props.imageUrl}
is getting properly passed as a prop
, it isn't rendering in the HTML - it just renders as {this.props.imageUrl}
. How can I make the variable pass through properly into the HTML?
By using spread attributes, you can dynamically add (or override) whatever attributes you'd like by using a javascript object instance. In my example above, the code creates a disabled key (with a disabled value in this case) when the disabled property is passed to the Hello component instance.
To set a data attribute on an element in React, set the attribute directly on the element, e.g. <button data-test-id="my-btn"> or use the setAttribute() method, e.g. el. setAttribute('data-foo', 'bar') . You can access the element on the event object or using a ref . Copied!
You can simply pass the dynamic tag name as the first argument to the React. createElement() method (as it accepts a string tag name). For example: const type = (someCondition) ?
You should not wrap JavaScript expressions in quotes.
<option data-img-src={this.props.imageUrl} value="1">{this.props.title}</option>
Take a look at the JavaScript Expressions docs for more info.
Note - if you want to pass a data attribute to a React Component, you need to handle them a little differently than other props.
2 options
Don't use camel case
<Option data-img-src='value' ... />
And then in the component, because of the dashes, you need to refer to the prop in quotes.
// @flow class Option extends React.Component { props: { 'data-img-src': string }
And when you refer to it later, you don't use the dot syntax
render () { return ( <option data-img-src={this.props['data-img-src']} >...</option> ) } }
Or use camel case
<Option dataImgSrc='value' ... />
And then in the component, you need to convert.
// @flow class Option extends React.Component { props: { dataImgSrc: string }
And when you refer to it later, you don't use the dot syntax
render () { return ( <option data-img-src={this.props.dataImgSrc} >...</option> ) } }
Mainly just realize data-
attributes and aria-
attributes are treated specially. You are allowed to use hyphens in the attribute name in those two cases.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With