Intro to React - JSX and Elements

maxdemaio

Max DeMaio

Posted on February 23, 2022

Intro to React - JSX and Elements

React is a modern JavaScript library for building interactive user interfaces. In this blog post, we'll get a brief introduction and how to get started with React.

Demos:


Why React?

Let’s look at an Instagram post I’ve made. The moment I “like” a post the status changes. The heart becomes red, the number of likes changes, and we can immediately see this on the web page.

Instagram post example

Instagram has to do the changes by updating the DOM tree of the page and re-rendering the page in the browser. The application also has to show other Instagrammers that I’ve liked this post if they’re looking at it too.

As of 2019, it was recorded that Instagram had over 1 billion users (Revista Economică, 57). As of the date of this blog post, that number has probably soared to over 2 billion users. Considering the size of Instagram, it'd be a challenge to ensure efficient and consistent DOM manipulation. Luckily, Facebook had already created a frontend library called React specialized in this.

What is React?

To make it short and snappy, React.js is a JavaScript library. It allows developers to create user interfaces (UIs) and make the development of UI components easy and modular. It was created by Jordan Walke, a software developer at Facebook and it was open sourced to the world by Facebook and Instagram.

React Features

  • Components/JSX: components are the building blocks of React applications. Think of HTML templates but we write them using a special syntax called JSX. After compilation, JSX expressions become JavaScript function calls and evaluate to JavaScript objects. Components can be simple or stateful.
// Simple component that will display "Yo {props.name}!"
class YoMessage extends React.Component {
  render() {
    return <div>Yo {this.props.name}!</div>;
  }
}

ReactDOM.render(
  <YoMessage name="MaxMayo" />,
  document.getElementById('yo-example')
);
Enter fullscreen mode Exit fullscreen mode
// Classic timer stateful component
class Timer extends React.Component {
 constructor(props) {
 super(props);
 this.state = { seconds: 0 };
  }

 tick() {
 this.setState(state => ({
      seconds: state.seconds + 1
    }));
  }

 componentDidMount() {
 this.interval = setInterval(() => this.tick(), 1000);
  }
Enter fullscreen mode Exit fullscreen mode
  • Virtual DOM: Instead of rebuilding the entire DOM tree for updates, React makes use of the virtual DOM. The virtual DOM is a lightweight copy of the actual DOM. React will update exactly which virtual DOM objects have changed through diffing.
  • Unidirectional Data Flow: React has a waterfall like concept of transferring data to other parts of the application. State is passed to the view and child components. Actions are triggered by the view and can update state.
  • SEO/Performance: you can even run React on the server for SEO, performance, code sharing and flexibility.

Getting Started

We can use create-react-app to bootstrap a React application. The only prerequisite is that we need Node.js version 10+. We can check the Node version in our system with the command node -v.

Off to the races!

npx create-react-app my-app
cd my-app
npm start
Enter fullscreen mode Exit fullscreen mode

Here’s a quick explanation of the folder structure generated by create-react-app:

Files Purpose
node_modules/ All app dependencies live in this folder
public/ This folder contains the public static assets of the application
public/index.html This is the first page that gets loaded when we run the application
src/ All application related files/folders are created in this folder
src/index.js The entry point of the application
package.json Contains the dependencies of the React application

If we observe the index.js file we can see the following:

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);
Enter fullscreen mode Exit fullscreen mode

ReactDOM.render() renders an element or component to the virtual DOM. The first parameter specifies what needs to be rendered. The second argument specifies where to render. A smaller example without components would look like this:

ReactDOM.render(<h1>Yo, world!</h1>, document.getElementById('root'));
Enter fullscreen mode Exit fullscreen mode

Babel compiles JSX down to React.createElement() calls. So these examples are identical:

const myElement = <h1 className="yo">Yo, world!</h1>;
Enter fullscreen mode Exit fullscreen mode
const myElement = React.createElement('h1', { className: 'yo' }, 'Yo, world!');
Enter fullscreen mode Exit fullscreen mode

Unlike browser DOM elements, React elements are cheap to create because they’re plain JavaScript objects. Our React.render() would render these React elements since Babel compiles JSX down to React.createElement() calls. Then, React.createElement() creates objects aka React elements that generally look like this:

// Simplified structure
const myElement = {
  type: 'h1',
  props: {
    className: 'yo',
    children: 'Yo, world!',
  },
};
Enter fullscreen mode Exit fullscreen mode

These React elements are representations of what we’d want to see on the screen. Note, elements make up components. React reads these objects and uses them to make the DOM and update it.

Conclusion

In this blog post we learned about what React is and how to start a React application. In future blog posts I’ll dive into the main concepts of React with helpful demos. Stay tuned!

Works Cited

💖 💪 🙅 🚩
maxdemaio
Max DeMaio

Posted on February 23, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related