YogeshChauhan . com

How to add multiple components in React app?

in React on June 6, 2021

Let’s spin up the basic app using these steps.

Create React App

Let’s go inside the src folder to make some changes.

Delete these files:

  • reportWebVitals.js
  • logo.svg
  • App.css
  • App.test.js
  • setupTests.js

Replace the index.js code with this code:

In the following code, the last line represents a React component with a name App. It checks for the element with id “root” and renders its content into it.


import ReactDOM from "react-dom";
import App from "./App";

ReactDOM.render(<App />, document.getElementById("root"));


Replace app.js with this code:

This code replace the regular function with an arrow function and saves the value in a variable.


import React from "react";
const App = () => (
  <div>
    <p>Hello there!</p>
  </div>
);

export default App;


The function above has HTML code. Let’s convert that into JSX.

Project created using create-react-app are compiled automatically and the compilation is handled by Babel.

Multiple components

Let’s define a new component and add it into the main App component.


import React from "react";
const Name = () => {
  return (
    <div>
      <p>My name is Yogesh.</p>
    </div>
  );
};

const Greetings = () => {
  return (
    <div>
      <p>Nice to meet you!</p>
    </div>
  );
};

const App = () => {
  return (
    <div>
      <h1>Hey there!</h1>
      <Name />
      <Greetings />
    </div>
  );
};

export default App;


React components are reusable and that’s why you can add the same component multiple times too!

amazon

Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 How to Use SQL MAX() Function with Dates? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

Jun 16 What are Stored Procedures for SQL Server? Jun 16 What are Class Constants in PHP? Jun 15 A short basic guide on states in React Jun 15 How to define constants in PHP? Jun 15 How to define visibility for a property in PHP? Jun 15 How to use @if and @else in SCSS?

You might also like these

:in-range and :out-of-range selector in CSSCSSHow to create a Child Theme in WordPress?WordPressLIKE and ILIKE Operators in PostgresPostgresWHERE Clause in PostgresPostgresValues and Types Basics in JavaScriptJavaScriptHow to link/add CSS file to HTML Document?CSS