Simple React JS Tips

Haven’t posted in a while, but I’ve learned a whole bunch of technologies over the last few years. I’ve been learning react js for a contracting job of mine, so I thought I’d share some tips, as well as create this blog post in order to remember the things I learned.

React is pretty similar to Polymer. I’d say it’s a mix of Polymer, html, css, and javascript. It allows you to *componetize* special elements you create, so you can easily access it again. I’d say I like Polymer better though.

Few tips/things to remember:

{} – if you want to call a variable or function inside a return html tag. So for example, if you are creating a simple render() function for a new class that is an extension of React.Component:

rendertest(i) {
   return {
      <div>
         <h1>{i}</h1>
      </div>
          }
}

So if you call rendertest(4), it will return:

<div><h1>4</h1></div>

This also works for function calls so if you want to call a function inside your html tags that resides in the javascript code, you can do so by

{call()}

props – In React you see props a lot. This is essentially a parameter. Not a function parameter, but you can think about it as an html attribute. So lets say you create a class called testPizza. And you want to create a parameter called pizza..

<testPizza pizza="I LOVE PIZZA"></testPizza>

You can access your pizza parameter by using {this.props.pizza}.

Full code example:

class testPizza extends React.Component {
   render() {
      return <h1>{this.props.pizza}</h1>

   }


}
Then you can call it like: <testPizza pizza="I LOVE PIZZA" />

And it will show up like this:


I LOVE PIZZA


this.state

This allows you to set private state variables for your class. For example

this.state = {
value = null;
};

Then you can set state by:

this.setState({value: 'PIZZA IS GOOD'})