Conditionally adding attributes to an HTML element in React

This week, I've been working on a React component, where the rendered HTML needed some conditional attributes to be included, based on the props passed in.  

I found something neat - you can add an array of attributes to an HTML element using the spread operator.

For example, this code ...

 var divAttributes = { "data-ride":"carousel", "data-interval":"10000" };  
 return <div {...divAttributes} className="carousel">...</div>  

... would generate this output ...

 <div data-ride="carousel" data-interval="10000" class="carousel">...</div>  

As an old-hand jQuery hack, I'm really enjoying migrating my projects to React.  In particular, the way it allows you to modularise your front-end code - making everything much easier to maintain (and reusable).

Comments