...

/

Building an App with Components

Building an App with Components

Learn how JavaScript and React enhance web apps for user-friendly experiences and multi-page functionality.

Creating an app

To start building an application, here's a block of HTML we can start with:

<!Doctype HTML>
<html lang="en">
<body>
<div id="root"></div>
</body>
</html>

These days, we have more and more SPAs that update parts of pages on the fly, which makes using the website feel like a native application. A quick response time is what we are aiming for. JavaScript is the language to deliver this goal, from displaying the user interface to running application logic and communicating with the web server.

To add logic, React takes over one section of the HTML to start a component:

<script>
const App = () => {
// Return an h1 element with the text "Hello World."
return <h1>Hello World.</h1>;
}
// Get the root element by its ID ("root")
const rootEl = document.getElementById("root");
// Render the App component into the root element using ReactDOM
ReactDOM.render(<App />, rootEl);
</script>
React component and rendering logic

The render function in the preceding code, provided by ReactDOM, accepts two input arguments, which are a React element <App /> and a DOM element, rootEl. rootEl is where we want React to render, in our case, a DOM node tagged with the root ID. What React renders to rootEl can be found defined in a function component, App.

It’s important to tell the difference between App and <App /> in React. App is a component, and there has to be a ...