React: 2 - Our First React Web Component
In my previous blog I introduced React – a new(ish) JavaScript library for building “Web Components”. In this post I will start to dive deeper by building our first React Web Components.
Hello World
Every new language/framework has a way to build the class “Hello World” program, and below is the simplest React program that does just that.
In this program the global React object’s render method is used to render the Hello World in an h1 tag. The render method takes two parameters – the first parameter is what to render and the second parameter is where to render it – in this case inside the element with id=example.
React’s JSX syntax
What jumps out when looking at the React Hello World is that there is something that looks like HTML embedded in the code. This is actually not HTML but JSX – React’s JavaScript syntax extension. In order for the example above to work the JSX needs to be “transpiled” into pure JavaScript. However, for ease of development React provides an “in-browser” transpiler – JSXTransformer.js.
The JSX in our previous example is transformed to the following JavaScript
You don’t have to use JSX to write React programs but it makes the “HTML” more readable and is easier to understand.
HelloMessage React Component
Our example is not really a component. It is a React program but it is not a Component. Lets rewrite the code as a HelloMessage component.
In this rewritten example we create a “HelloMessage” component by using the createClass method of the global React object. We define a public render method for the HelloMessage component which returns the “HTML” we wish to render. The props property of the component contains the properties that have been passed to the component, and we render the name property.
We then call our component using the JSX statement
That’s it – our very first React component.
In my next blog post I will continue my exploration of this cool new library – stay tuned.