React Components

Jun 26, 2024

React Components

Overview

  • Components are the building blocks of any React application.
  • Each web page in React is made up of several components.
    • Example components: Navbar, Article, Sidebar.
  • Components contain their own templates and logic for specific content.
    • Example: Navbar component contains HTML for the navbar and JavaScript logic for actions like logging out.

Rendering Components

  • Initially, only a single component (App) is rendered.
  • Located in index.js file inside the src folder.
  • The App component is rendered to the DOM at the element with id="root".
  • Root Component: The first component rendered; more details will be covered later.

Example Component Structure

  • The App component is a function that returns JSX (not HTML).
    • Function can be an arrow function
    • Must start with a capital letter, e.g., App

JSX

  • Syntax similar to HTML but with some differences.
  • JSX is transpiled by Babel into HTML in the background.
  • Class Names: use className (camelCase) instead of class.
    • class is reserved in JavaScript.
  • JSX templates are converted to HTML and rendered to the DOM.

React Versions

  • In versions < 17, import React from 'react' was necessary at the top of the file.
  • In version 17 and above, this import is not needed.

Simplifying the Template

  • Removed unnecessary content inside the div with the class name App.
  • Added new div with the class content:
    <div className="content">
      <h1>App Component</h1>
    </div>
    
  • Removed the import for the logo that is no longer needed.

Exporting Components

  • Export component functions so they can be imported and used in other files:
    export default App;
    
  • Example of usage in index.js:
    import App from './App';
    
  • Rendered using ReactDOM library.