How to dynamically set HTML5 data attributes in JSX/Reactjs
Data attributes provide the ability to tag HTML markup with additional layers of data. They are frequently used to store information that would not be practical to put inside class
or id
attributes.
A data attribute is an attribute on an element that starts with data-test-info.
As data attributes are useful for semantic markup, there are plenty of scenarios where we want to interact with them in a React.js application.
For example, we might want to dynamically create a data attribute based on a prop received by our component.
So, how can you set a data attribute in JSX? To dynamically set a data attribute in JSX we need to use JSX brackets in our render function:
class Item extends React.Component { constructor(props) { super(props); } render () { const { dataAttribute } = this.props; return ( <div data-important-info={dataAttribute} >...</div> ) } }
- Using a prop value, the value of
data-important-info
is set dynamically. - Even though there dashes in
data-important-info
we can still specify it in JSXdiv
element - If we were rendering multiple
Item
components we could have a unique value for eachdata-important-info
attribute.
But this raises another question. What if our data attribute is coming from props, how can we access with its dashes?
Well due to the dashes, we need to refer to the prop in quotes.
render () { return ( <div data-important-info={this.props['data-img-src']} ></div> ) }
Even though data attributes aren’t essential for web app users, having easy access to them provides a better developer experience with easier access to HTML data.