Saturday, 2 January 2016

JSX Gotchas

When working with JSX and React there are a few things to be aware. This list will avoid any headaches when trying to debug your application or website.

1. ClassName

In JSX any html tags with ‘class’ will have to be renamed to ‘className’. This is because ‘class’ is a reserved word in Javascript.

2. Self closing tags

All tags in JSX must be closed with a self closing tag, <Example /> or a corresponding closing tag, </Example>.

3. Inline Styles

Inline styles are not strings like standard HTML, they are Objects. The objects’s styles must be camel case, and the value as a string. Any vendor prefixes must be capital case.

var styles = {
textAlign:’center’,
color:’red’
}

<div style={styles}></div>

4. Render nested

The render method can only return one node. Therefore if you have more than one component inside the render method, it must be wrapped in a containing div, span or component.
var wrapper = React.createClass({
  render:function(){
    return (
      <div>
        <div></div>
        <div></div>
      </div>
    )
  }
});

5. Always use a key attribute for list components

When you are rendering a list of tags then you will need to use a key attribute.
var listExample = React.createClass({
  render:function(){
    <ul>
    {this.props.items.map(function(i){
      return <li key={i}>{items.name}</li>
    })}
    </ul>
 }
});

0 comments:

  COPYRIGHT © 2014 · ILIKE2FLASH · Theme by Ourblogtemplates

Back to TOP