A key thing to understand about React is that its rendering engine is kept separate from the core library. Thanks to that separation of concerns, many different renderers have been created.
For example, react-dom is the default renderer for the web platform; it takes care of rendering components to HTML DOM elements. To do that, React DOM uses a virtual DOM, a technique that we have discussed in the previous chapters and that React has made popular.
When targeting mobile platforms, there is a more adequate solution that you can use: react-native. Check out the resources listed at the end of this chapter to discover other ones.
React applications may be made up of components (for example, dumb components) and pages (that is, smart/presentational components), so we'll remain in a familiar environment since we will keep decomposing the user interface of our applications in the same way as we did so far: with encapsulated and reusable components.
One major difference between React components and Angular ones is that React has chosen to mix markup and logic together in the same files. This shouldn't be too shocking as we have seen a sort of similar idea being applied with single-file Vue.js components.
Here's the unavoidable Hello world with React, assuming that both React and ReactDOM have been loaded on the page beforehand:
ReactDOM.render( <h1>Hello, world!</h1>, document.getElementById('root') );
This code uses the render function of ReactDOM to render a heading tag. The result is added to the DOM of the element that has the root identifier (this name is arbitrary, it must just be part of the actual DOM of the page!)
You might be surprised by the syntax. In the preceding render function, we did mix HTML markup and JavaScript code together; that was no mistake. This indeed goes further than what Vue.js does with SFCs.
This code snippet is actually written in JSX, a syntax extension for JavaScript initially created for React, but also supported by other libraries (for example, Vue.js!). We will discuss JSX soon, so don't worry about it for now.
Here's a second example that defines and renders a custom React component:
function DisplayMessage(props) { return <div>Welcome to React {props.name}!</div>; } ReactDOM.render( <DisplayMessage name="foo" />, document.getElementById('container') );
The DisplayMessage function is a very basic example of React component: a simple function that accepts a props object as input and returns elements defined with JSX. Props are indeed the properties of the component (we'll come back to this later). To render our component, we do the same as before, this time using our custom DisplayMessage component.
We'll explore other ways to create React components in the next sections, but keep in mind that defining components using functions is considered to be the idiomatic React way. We'll explore why this approach is preferred later on.
Let's continue.