Learning React, a few helpful notes

It's been mostly a pleasure learning React.js over the past few weeks. Many things I didn't know at first now seem like second nature.

However, I wish I would have had these tips when I was learning:

How do you render markup or html in your data?

If you load your JSON data, there may be some markup, like italicized words for names of publications. But React renders this as text:

After loading your JSON and passing it as a prop, this.props.publication = '<em>New York Times</em>'

The output is:

<em>New York Times</em>  

You want it to be:

New York Times

Inserting innerHTML is considered bad, because if you insert invalid markup, it can break the rest of your page. XML can also be inserted and it can be a security risk.

But it is possible, and React has a helper function to 'sanitize' the potential bad parts. As you can see from the name, they want you to know it is dangerous:

dangerouslySetInnerHTML

So, in JSX, you set the innerHTML as a prop — not inside the tags

Bad:

<h2>{this.props.publication}</h2>  

Good:

<h2 dangerouslySetInnerHTML={{  
       __html: this.props.publication,
       sanitize: true
       }}>
</h2>  

It works for non-visible markup too

Set styles in render() using dangerouslySetInnerHTML.

<style type='text/css' dangerouslySetInnerHTML={{__html: '::-ms-clear {display: none;}' }} />  

This hack to hides the cancel button on <input> elements in IE (in case you want to style it yourself or use Bootstrap)


Wait for data to load before render function is called

The real way to do this is to set your initial state to empty parameters. But what if you don't want anything to show until data is ready?

In your render function, return something temporary (like a spinner or loading.gif) until the data is loaded. When you setState, render() fires again because the data changed:

  constructor() {
    super();
    this.state = {
      data: null
    };
  }
  componentDidMount(){
    setTimeout( ()=>{
      this.setState({ data: 'I coulda been async.' })
    },3000)
  }
  render() {
    if (this.state.data === null) {
      return <div><p>Wait for it...'</p></div>
    }
    return <div className="main container">
      <p>Here’s the data: { data } </p>
    </div>
  }