Creating and Nesting Components

ReactReactBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

Welcome to the React documentation! This lab will give you an introduction to creating and nesting components.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL react(("`React`")) -.-> react/FundamentalsGroup(["`Fundamentals`"]) react/FundamentalsGroup -.-> react/jsx("`JSX`") react/FundamentalsGroup -.-> react/components_props("`Components and Props`") subgraph Lab Skills react/jsx -.-> lab-100371{{"`Creating and Nesting Components`"}} react/components_props -.-> lab-100371{{"`Creating and Nesting Components`"}} end

Creating and Nesting Components

The React project have already been provided in the VM. In general, you only need to add code to App.js.

Please use the following command to install the dependencies:

npm i

React apps are made out of components. A component is a piece of the UI (user interface) that has its own logic and appearance. A component can be as small as a button, or as large as an entire page.

React components are JavaScript functions that return markup:

// App.js
function MyButton() {
  return <button>I'm a button</button>;
}

Now that you’ve declared MyButton, you can nest it into another component:

// App.js
export default function MyApp() {
  return (
    <div>
      <h1>Welcome to my app</h1>
      <MyButton />
    </div>
  );
}

Notice that <MyButton /> starts with a capital letter. That’s how you know it’s a React component. React component names must always start with a capital letter, while HTML tags must be lowercase.

The export default keywords specify the main component in the file. If you’re not familiar with some piece of JavaScript syntax, MDN and javascript.info have great references.

To run the project, use the following command. Then, you can refresh the Web 8080 Tab to preview the web page.

npm start

Summary

Congratulations! You have completed the Creating and Nesting Components lab. You can practice more labs in LabEx to improve your skills.

Other React Tutorials you may like