How do I dynamically set HTML5 data- attributes using react?
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?
Solution 1:
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.
Solution 2:
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.