Why React?

React.js is a JS library developed by engineers at FaceBook.

  • Fast. Apps made with React can handle complex updates and still feel quick and responsive.
  • Modular. Instead of writing a large wall of code, you can write many smaller, reusable files.
  • Scalable. React performs best with large programs that display a lot of changing data.
  • Flexible. You can use React for many purposes, not just making a web app.
  • Popular. You’ll be more employable.

JSX

JSX is a syntax extension for JavaScript. It was written to be used with React.

A JSX compiler has to translate any JSX into regular JS before it reaches the browser.

Example of a JSX element:

<h1>Hello world</h1>

JSX elements can go in a JS variable, passed to a function, stored in an object or array.

const navBar = <nav>I am a nav bar</nav>;

Like HTML, JSX can have attributes:

const title = <h1 id=“title”>Intro to React.js: Pt 1</h1>;

Multi-line JSX expressions must be wrapped in ()

(
  <a href="https://www.example.com">
    <h1>
      Click me!
    </h1>
  </a>
)

JSX expressions must have exactly one outermost element:

const paragraphs = (
  <div id="i-am-the-outermost-element"> // <---
    <p>I am a paragraph.</p>
    <p>I, too, am a paragraph.</p>
  </div>                                // <---
);

Rendering JSX

ReactDOM.render(<h1>Hello world</h1>, document.getElementById('app'));

ReactDOM is the name of a JS library that contains several React-specific methods that deal with the DOM.

ReactDOM.render() is the most common way to render JSX. It takes a JSX expression, creates a corresponding tree of DOM nodes and adds that tree to the DOM.

<h1>Hello world</h1> is the first argument being passed to the ReactDOM.render().

document.getElementById('app') tells ReactDOM.render() which element to append the first argument <h1>Hello world</h1>to.

The first argument that goes into ReactDOM.render() has to be a JSX exp or evaluate into one:

const toDoList = (
  <ol>
    <li>Learn React</li>
    <li>Become a Developer</li>
  </ol>
);

ReactDOM.render(
  toDoList,  // a variable that evaluates to a JSX expression
  document.getElementById('app')
);

The Virtual DOM

ReactDOM.render() only updates DOM elements that have changed. React's reputation for performance have come from this innovation.

In summary, here's what happens when you try to update the DOM in React:

  1. The entire virtual DOM gets updated.
  2. The virtual DOM gets compared to what it looked like before you updated it. React figures out which objects have changed.
  3. The changed objects, and the changed objects only, get updated on the _real _DOM.
  4. Changes on the real DOM cause the screen to change.

results matching ""

    No results matching ""