React Episode 0

In this blog, I would explain why we have JSX and then a little bit about React.

Say, we want to insert a h1 element Hello World after the id = ‘root’ element in the page.

Vanilla JS code would be

let heading = document.createElement("h1");

let text = document.createTextNode("Hello World");
        
heading.appendChild(text);

let element = document.getElementById('root');
        
element.appendChild(heading);

We can see that this is really inconvenient. Then what do smart developers do?

JSX

It is an extension of JavaScript, short for JavaScript XML. It helps us write less code. Look at the following example, which achieves the same result as above using JSX & React.

const element = <h1>Hello, world!</h1>;
ReactDOM.render(
  element,
  document.getElementById('root')
);

JSX converts HTML tags into React elements, which can be used later by ReactDOM. In the conversion process, it actually calls React.createElement() method.

What does ReactDOM and render in the code mean?

ReactDOM uses virtual DOM (Document Object Model). DOM treats XML/HTML document as tree structure wherein each node is an object representing a part of the document.

Render method is to put a React element into the DOM.

Can you talk more about React?

Sure. From above, we can find that React is associated to what we see, which is called UI (User Interface). Also as the name shows, React reacts to changes. React is built for dynamic UI.

Another important concept in React is component. React components are small, reusable pieces of code that return a React element to be rendered to the page. 

I would say component is just like Lego bricks that we can reuse to build something bigger.

Summary

JSX and React makes DOM modification easier. They work together but you don’t need to write JSX in React. React reflects the philosophy of reducing repetition in software development.

References

  1. https://reactjs.org/docs/introducing-jsx.html
  2. https://en.wikipedia.org/wiki/Document_Object_Model

One thought on “React Episode 0

Leave a comment