react

React: Hello World and JSX

This is a typical Hello World implementation in React in JSX file. It shows one of two ways you can write components, and how you pass data to a components.

import React, { Component } from 'react';
import ReactDOM from 'react-dom';

class App extends Component {
  render() {
  return (
    <h1>Hello {props.name}</h1>
  )
  }
}
ReactDOM.render(<App name="world"/>, document.getElementById('root'));

Most React Components are written as classes Extending from the React.Component class, and the only method a component have to implement is “render”. It returns either a new component or markup.

One side note: a component have to return one root node. For example:

<!-— It can't return: -->
<h1></h1>
<p></p>

<!-— But it can return -->

<div>
   <h1></h1>
   <p></p>
</div>

JSX

JSX is the syntax we use to define markup with React. It combines JavaScript code and markup together in a very flexible and powerful way and is without doubt my favorite thing about React. Everything you use in JSX that isn’t Javascript code, is technically components. All HTML tags are implemented as Components in React. For example the h2-tag is a h2 component inside the React package, with the appropriate params defined to an HTML attribute; note: they are not always the same though.

Everything that you wrap in HTML tags (either self-closing or not) are components and everything inside curly braces are JavaScript code.

For example:

import react from 'react'
const Comp = () =>
    <div>
        <Header title="Hello World"/>
  <Menu />
  <Main>
      <Router>
        </Main>
        <Footer/>
</div>

That would be a common starting point for a simple React app.

I personally think that JSX is the first templating system I have seen that is powerful, without adding a lot of syntax that isn’t plain JavaScript and HTML. Most other ways to template I have seen almost turn it into a language of its own that let you combine code and markup.

The great thing about this is that almost everyone gets it straight away.

Leave a Reply