How do I dynamically set HTML5 data- attributes using react?

Reactjs

Reactjs Problem Overview


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?

Reactjs Solutions


Solution 1 - Reactjs

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 - Reactjs

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionYPCrumbleView Question on Stackoverflow
Solution 1 - ReactjsMichelle TilleyView Answer on Stackoverflow
Solution 2 - ReactjsMark SwardstromView Answer on Stackoverflow