Computer scienceFrontendReactIntroduction to React

Overview of the basic program

8 minutes read

Once you've completed the installation steps and set up the development environment for your project, you can begin working on a React project. In this topic, you'll learn what a basic React project looks like and how to modify the files to start developing.

Starting for the first time

Once you've created your project, you can navigate to the project directory using the command mentioned below, assuming your project's name is basic-react-app:

cd basic-react-app

Within the project directory, start the development server using this command: npm start or yarn start. Your browser should display something similar to this:

Starting React project in the browser

Running npm start in your React project initiates a development server with an inclusive hot reloading feature; this feature lets you view your adjustments in real-time, without manual refresh. Hence, whenever you modify your React code and save the changes, the development server detects the updates and instantly refreshes the application viewed in the browser.

If the browser fails to load automatically, you can manually navigate to this address: http://localhost:3000 to view the results.

Starting file structure

When you initiate a new React project, it establishes a basic beginning program with a file structure and some preset files. Here is what it could look like:

Now, let's review the essential components of the beginning program:

public folder:

  • index.html: This file is the entry point to your React application. It houses a <div> element with an id of "root" where your React components will render.

  • Other files: This folder can host other static files like images, fonts, or favicon.ico.

src folder:

  • index.js: This file is the kickoff point for your React application. It imports the ReactDOM library and the root component (App), rendering it into the DOM by targeting the root element in the index.html file.

  • App.js: This is the primary component of your application. It acts as the container for other components and is in charge of rendering the user interface.

  • App.css: This file holds styles specific to the App component.

  • App.test.js: This file contains tests for the App component.

Other Files:

  • package.json: This file carries metadata about your project and its dependencies. It also features scripts to start, build, and test your application.

  • package-lock.json: This file is automatically generated and helps maintain consistent installations of dependencies across various environments.

  • README.md: This file delivers information and instructions about your project.

The beginning program sets up a development server that reloads your application automatically when you modify the code. It also supports modern JavaScript features, CSS preprocessing, and more right out of the box.

Let's delve into the starting code next.

Examining the starting code

Let's check out some key files and their code. We'll begin with the index.js that's the root component of a React app:

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

At the top of the file, you see the imports used in this script. Importing react allows you to use React components and JSX syntax. The index.css file contains styles for the root component, App, and other components in your application.

The App component comes from the App.js file. This component is the main part of your application and it houses other components.

After the imports, you'll see the root line, which makes a root instance by using ReactDOM.createRoot(). The createRoot() function makes a new root for concurrent mode rendering. It uses the DOM element you want to render components in as its argument. Here, it targets the element with the id "root" (found in the index.html file) using document.getElementById('root'). The root instance is the root of the React component tree.

Finally, we get to the root.render part. This function call puts the React components into the DOM. It takes one argument:

  • The JSX code that represents the component tree you want to render. Here, the Appcomponent is inside <React.StrictMode>, which activates additional checks and warnings during development.

If you run the React application with this code, it creates a root instance with ReactDOM.createRoot() and sets the target DOM element for rendering. After that, it uses the root.render() method to render the App component into the selected root.

React uses a virtual DOM to render components. With this approach, React reduces the number of direct changes it needs to make to the actual slow and inefficient DOM. Instead, it makes updates on the lighter virtual DOM and only applies necessary changes to the actual DOM, resulting in faster and more efficient UI rendering.

Now, we'll briefly cover App.css and index.html before moving onto App.js.

App.css:

.App {
  text-align: center;
}

.App-logo {
  height: 40vmin;
  pointer-events: none;
}

.App-header {
  background-color: #282c34;
  padding: 20px;
  color: white;
}

.App-link {
  color: #61dafb;
}
/* ... */

The CSS styles in App.css add basic styling to center the content, set the background color, and choose the colors for the header and link. Your starting program might have different styles, but the key point is that this is where the style for App.js originates from.

Index.html:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta
      name="description"
      content="Web site created using create-react-app"
    />
    <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />

    <title>React App</title>
  </head>
  <body>
    <noscript>
      You need to enable JavaScript to run this app.
    </noscript>
    <div id="root"></div>
  </body>
</html>

You should be familiar with most of the content in the generated index.html in the public folder, but take note of these key tags:

  • <noscript>: This tag provides alternative content for users who have disabled JavaScript in their browsers. Here, it displays a message asking the user to enable JavaScript.

  • <div id="root"></div>: This empty <div> element with an id of "root" is where the React components will be rendered. The code injects the <App /> component from the React code into this element.

The index.html file acts as the entry point for your React application. It provides the basic structure and necessary tags for rendering the React components and references various assets like icons and the manifest file.

Modifying the app.js

Now, you'll examine App.js, which is fundamental to our application:

import React from 'react';
import logo from './logo.svg';
import './App.css';

function App() {
  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Edit <code>src/App.js</code> and save to .
        </p>
        <a
          className="App-link"
          href="https://reactjs.org"
         
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
    </div>
  );
}

export default App;

At the start, you see we import the react module, along with styles and the logo. The App function defines a functional component named App. Functional components are a simple way to define components in React using JavaScript functions. The App component serves as the base for our application, returning something that appears to be HTML markup but is, in fact, JSX code. This returned value establishes the structure and content of the App component.

The rest of the code bears a resemblance to familiar HTML tags, each of which may have different attributes such as className. The className attribute enables you to apply CSS class to the element, styling the App component based on designs specified in the App.css file. There are attributes similar to HTML ones, along with the distinctive src={ logo } notation which links to the imported logo.svg above. This is characteristic of JSX, permitting variables or imports outside of the return function to be implemented within the HTML.

The file concludes with an export statement that designates the App component as the primary export of the App.js file. This allows other files to import and deploy the App component.

When the App.js component gets imported and rendered in the index.js file, the returned JSX code takes form in the DOM. This code lays down a basic form for an application, complete with a header, an image, a paragraph, and a link.

Below is how we update this code:

import React from 'react';
import logo from './logo.svg';
import './App.css';

function App() {
  const hello = 'Hello from my first React App!';
  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          { hello }
        </p>
      </header>
    </div>
  );
}

export default App;

This time, you declare a variable named hello and use it inside the p tag. Make sure to put { } brackets around the hello variable; it’s a necessary step to output its value.

Take a look at the outcome:

Modified React app, showing hello world.

If you miss out on closing the outer div tag, a compile error will show up in your browser:

Compile error on browser

In conclusion, the App component acts as a basic React component, ideally set to display the "Hello from my first React App!" message inside a p element.

Conclusion

Congratulations! You just created a straightforward "Hello, World!" program using React. Now, you can edit the code in App.js to craft more intricate applications and discover the diverse features and functionalities of React. You've seen the initial program output and file structure. You also got an overview of some key files in the application.

6 learners liked this piece of theory. 2 didn't like it. What about you?
Report a typo