To use React in your newly created project, load two React scripts from an external website called unpkg.com:
html
Instead of directly manipulating the DOM with plain JavaScript, remove the DOM
methods that you had added previously, and add the
ReactDOM.createRoot() method to target a specific DOM element and create a root to display your React Components in. Then, add the root.render() method to render your React code to the DOM.
This will tell React to render our <h1> title inside our #app element.
html
If you try to run this code in the browser, you will get a syntax error:
bash
This is because <h1>...</h1> is not valid Javascript. This piece of code is
JSX.
JSX is a syntax extension for JavaScript that allows you to describe your UI in a familiar HTML-like syntax. The nice thing about JSX is that apart from following three JSX rules, you don't need to learn any new symbols or syntax outside of HTML and JavaScript.
But browsers don't understand JSX out of the box, so you'll need a JavaScript compiler, such as a Babel, to transform your JSX code into regular JavaScript.
To add Babel to your project, copy and paste the following script in your
index.html file:
html
In addition, you will need to inform Babel what code to transform by changing
the script type to type=text/jsx.
html
To confirm it's working correctly, open your HTML file in the browser.
Comparing the declarative React code you just wrote:
html
to the imperative JavaScript code you wrote in the previous section:
html
You can start to see how using React enables you to cut down a lot of repetitive code.
And this is exactly what React does, it's a library that contains reusable snippets of code that perform tasks on your behalf - in this case, updating the UI.
Additional Resources:
You don't need to know exactly how React updates the UI to start using it, but if you'd like to learn more, here are some additional resources:
- UI trees
- Writing markup with JSX
- react-dom/server sections in the React Documentation.
While you can learn JavaScript and React at the same time, being familiar with JavaScript can make the process of learning React easier.
In the next sections, you will be introduced to some core concepts of React from a JavaScript perspective. Here's a summary of the JavaScript topics that will be mentioned:
While this course does not dive into JavaScript, it's good practice to stay up to date with the latest versions of JavaScript. But if you don't feel proficient in JavaScript yet, don't let this hinder you from starting to build with React!
Mark this chapter as finished to continue
Mark this chapter as finished to continue