ReactJS-The Beginner Master Class
  • React In the Beginning
    • Lesson 1 - Demo: Build a Simple React App - Fast
    • Lesson 2 - HTML Review
    • Lesson 3 - CSS Review
    • Lesson 4 - Modern JavaScript (JSX) Patterns
    • Lesson 5 - Set up Dev Environment
    • Hands-on Practice
  • React Fundamentals
    • Lesson 1 - Understanding Old vs New Way of Building Web Apps - SPAs
    • Lesson 2 - Motivation for Using React as the Solution to Vanilla JS
    • Lesson 3 - What is ReactJS - How it Works
    • React Code Along from Scratch
    • Lesson 4 - Create and Run a React Project with Vite - Full Overview
    • Lesson 5 - Create Hook by State Management in React
    • Lesson 6 - React Project File and Folder Walkthrough
    • Lesson 7 - JSX and How React Treats the DOM & JSX Compilation(by Babeljs) - Overview
    • Lesson 8 - Understanding the Main Files - App.jsx and main.jsx
    • Lesson 9 - Props and One-Way Data Flow - Overview
    • Lesson 10 - Google Bookshelf App - Ver 1.0
    • Hands-on Practice I
    • Hands-on Practice II
  • React State and Styling
    • Lesson 1 - Pulling Book Data from a Different Data File
    • Lesson 2 - Overview of How State Works in React
    • Lesson 3 - RandomQuote App
    • Lesson 4 - Lifting State Up - React Pattern Overview
    • Hands-On - Simple Counter
  • Forms and Interactivity - Grocery List App
    • Lesson 1 - Setup a Simple Form and Input
    • Lesson 2 - Build Form Profile App Using Multi-input Form Data
    • Hands-on : Build a Grocery List App
  • Connecting to the Backend - Consuming APIs - UseEffect Hook
    • Lesson 1 - Connecting to the Back End - Understanding Side Effects, Hooks and useEffect - Overview
    • Lesson 2 - Fetching Data from the Backend the Right Way with useEffect Hook
    • Lesson 3 - Setting Up Loading State
    • Hands-on :Use Dependency Array and Adding Values that Control Side Effects
  • Solo Project 1
  • RESTful APIs :Build a BookSearch App -Ver 2.0
    • Lesson 1: Build and test RESTful APIs with Postman
    • Lesson 2 - BookShelf App Structure
    • Lesson 3 - Create NavBar.jsx Component
    • Lesson 4 - Create Footer Component
    • Lesson 5 - Create BookList.jsx Component
    • Lesson 6 - Create BookCard.jsx Component
    • Lesson 7 - Creating Custom Hooks - useBooks and api-client
    • Lesson 8 - Controlling Network Activities in React with AbortController
    • Lesson 9 - Show Book Details in a Modal - Working
    • Lesson 10 - Bookshelf App Summary
  • Multi-Page Applications (MPAs)
    • Build a Multi-Page React Application
    • Multi-Page React Application
    • Hands-on Practice
  • Backend Frameworks-NEXT.JS
    • Migrating from React to Next.js
    • Lesson 1: Key Concepts of NodeJS and Express for Backend Web Development
    • Lesson 2: How to set up a new Next.js project
    • Lesson 3: How to create Layouts and Pages
    • Hands-on Practice 1
    • Hands on Practice 2
      • New Project & Folder Structure
      • File-Based Routing
      • Server vs Client Components & Router Hooks
      • Start On The Navbar
      • Navbar Links, Dropdowns & React Icons
      • Active Links & Conditional Rendering
      • Homepage Components
      • Properties Page
      • Property Card Dynamic Data
      • Home Property Listings
      • Custom Not Found & Loading Pages
  • Git and GitHubs
    • Git Installation
    • Git Commands
    • GitHub Repository
    • Hands-on Practice
  • Database in Application
    • React Supabase CRUD
    • Hands-on: Note Taking App
  • NoSQL Database
    • Installing MongoDB Community Edition
    • System Env Path Setting
    • How to use MongoDB Shell
    • How to Connect and Use Mongosh in VS Code via MongoDB Extension
    • MongoDB Guide
  • Solo Project 2
  • Deployment and Web Hosting
    • Lesson 1. React+Vite+TS+Shadcn Project
    • Lesson 2. Deploying a React Vite App to Vercel from Vercel CLI
    • Lesson 3 Connecting to GitHub Repo and Automate Deployment
  • Solo Project 3
  • Final Term Project
    • Level 1 Team Project
    • Level 1 Team Project
    • Level 1 Team Project
    • Level 1 Team Project
    • Level 2 Team Project
    • Level 2 Team Project
    • Level 3 Team Project
    • Level 3 Team Project
Powered by GitBook
On this page
  1. React Fundamentals

React Code Along from Scratch

How to Write Components in React

1. How the Component Tree Structure in React Works and Nested Components

To build React applications with components, start with the following steps

// index.html - starter code
<html>
    <body>
        <div id="root"></div>
            <script src="https://unpkg.com/react@17/umd/react.development.js"></script>
            <script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
            <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
            <script type="text/jsx">
                const app = document.getElementById('root');
                ReactDOM.render(<h1>This is our web App!</h1>, app);
            </script>
    </body>
</html>
  1. Make sure you have the basic HTML structure set up. This includes the HTML and body tags.

  2. Include the necessary React libraries in your HTML file. You need React, React DOM, and Babel to transpile JSX. These are included via <script> tags that point to where the libraries are located.

  3. Create a container in your HTML where your React application will be rendered. This is typically a <div> with an id, such as <div id="root"></div>.

  4. Write a function for your component. React components are often created using functions. For example: function Header() { }.

  5. Capitalize the component name. React requires component names to be capitalized so it can recognize them as components.

  6. The function should return the JSX code that you want to render for that component. For example: return <h1>Hello World</h1>.

  7. To render the component, use the component as if it were an HTML tag, such as <Header />. This tells React to render the component.

  8. Use ReactDOM.render() to render your component into the desired DOM element. For example: ReactDOM.render(<Header />, document.getElementById('root')).

  9. When using an index on an HTML page, change JSX to Babel so that Babel reads the JSX properly.

// index.html - updated
<html>
    <body>
        <div id="root"></div>
            <script src="https://unpkg.com/react@17/umd/react.development.js"></script>
            <script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
            <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
            <script type="text/babel">
                function Header() {
                   return <h1>This is our web App!</h1>
                }
                
                const app = document.getElementById('root');
                ReactDOM.render(<Header />, app);
            </script>
    </body>
</html>

2. How the Component Tree Structure in React Works and Nested Components


// index.html -before nested
<html>
    <body>
        <div id="root"></div>
            <script src="https://unpkg.com/react@17/umd/react.development.js"></script>
            <script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
            <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
            <script type="text/babel">
                function Header() {
                   return <h1>This is our web App!</h1>
                }
                
                const app = document.getElementById('root');
                ReactDOM.render(<Header />, app);
            </script>
    </body>
</html>

// index.html - after nested
<html>
    <body>
        <div id="root"></div>
            <script src="https://unpkg.com/react@17/umd/react.development.js"></script>
            <script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
            <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
            <script type="text/babel">
                function HomePage() {
                   return (
                       <div>
                          <Header />
                       </div>
                }
                function Header() {
                   return <h1>This is our web App!</h1>
                }
                
                const app = document.getElementById('root');
                ReactDOM.render(<HomePage />, app);
            </script>
    </body>
</html>

3. How Props Work in React

// index.html - before props
<html>
    <body>
        <div id="root"></div>
            <script src="https://unpkg.com/react@17/umd/react.development.js"></script>
            <script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
            <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
            <script type="text/babel">
                function HomePage() {
                   return (
                       <div>
                          <Header  title="I love ReactJS" />
                       </div>
                )}
                function Header(props) {
                   console.log(props)
                   return <h1> {props.title} </h1>
                }
                
                const app = document.getElementById('root');
                ReactDOM.render(<HomePage />, app);
            </script>
    </body>
</html>

To build React applications with components, follow these steps, based on the sources:

  1. Utilize object destructuring to name property values in parameters, allowing for customization. For example, destructure the title from the header to access the title and customize the header.

  2. Incorporate template literals within the JavaScript code to further customize with HTML. For example, wrap the title in template literals to add text.

  3. Implement ternary operators for conditional rendering. This allows you to specify what to render based on a condition, such as ensuring a title prop meets a certain expectation. If the condition is not met, an error message can be displayed.

// index.html - props destructuring and operation
<html>
    <body>
        <div id="root"></div>
            <script src="https://unpkg.com/react@17/umd/react.development.js"></script>
            <script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
            <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
            <script type="text/babel">
                function HomePage() {
                   return (
                       <div>
                          <Header  title="I love ReactJS" author="Caleb Park" />
                       </div>
                )}
                
                function Header({ title, author }) {
                    console.log(title, author)
                    return (
                      <h1>
                        {' '}
                        {author === 'Caleb Park' ? title : 'No Book Found by' + author}
                      </h1>
                    )
              }
                
                const app = document.getElementById('root');
                ReactDOM.render(<HomePage />, app);
            </script>
    </body>
</html>

4. Mapping Through Lists in React

// index.html - before mapping through lists
<html>
    <body>
        <div id="root"></div>
            <script src="https://unpkg.com/react@17/umd/react.development.js"></script>
            <script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
            <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
            <script type="text/babel">
                function HomePage() {
                   return (
                       <div>
                          <Header  title="I love ReactJS" author="Caleb Park" />
                          <Header  title="I love NextJS" author="Samara" />
                       </div>
                )}
                
                function Header({ title, author }) {
                    console.log(title, author)
                    return (
                      <h1>
                        {' '}
                        {author ? title : 'No Book Found by' + author}
                      </h1>
                    )
              }
                
                const app = document.getElementById('root');
                ReactDOM.render(<HomePage />, app);
            </script>
    </body>
</html>

Iterate over lists using map function

It's common to have data displayed as lists in web applications, so you'll want to know how to render lists in React. Use the map method to iterate over an array and map each item to a list item using an arrow function. This should be done within the return statement, typically inside an unordered list (

When mapping through lists, ensure each child in the list has a unique key property. This helps React identify elements during updates in the DOM. If each item doesn't have a unique ID, you can use the item itself as the key, but it’s better to use an item ID, especially for large lists. If there are two items with the same key, an error will occur.

Names List

// Some code
const names =['Bakytbekov Jakypbai', 'Boobekov Dastan', 'Kuralbekov Nurjigit', Kyzdarbekov Nurdavlet'
]
// index.html - after mapping through lists
```html
<html>
  <body>
    <div id="root"></div>
    <script src="https://unpkg.com/react@17/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
    <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
    <script type="text/babel">
      function HomePage() {
        const names = [
          'Bakytbekov Jakypbai',
          'Boobekov Dastan',
          'Kuralbekov Nurjigit',
          'Kyzdarbekov Nurdavlet',
        ]
        return (
          <>
            <div>
              <Header title="I love ReactJS" author="Caleb Park" />
              <Header title="I love NextJS" author="Samara" />
            </div>
            <div>
              <ul>
                {names.map((name, index) => (
                  <li key={index}> {name} </li>
                ))}
              </ul>
            </div>
          </>
        )
      }

      function Header({ title, author }) {
        console.log(title, author)
        return <h1> {author ? title : 'No Book Found by' + author}</h1>
      }

      const app = document.getElementById('root')
      ReactDOM.render(<HomePage />, app)
    </script>
  </body>
</html>

5. What Are React Hooks and State in React

// index.html - Before hooks and using State
<html>
  <body>
    <div id="root"></div>
    <script src="https://unpkg.com/react@17/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
    <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
    <script type="text/babel">
      function HomePage() {
        const names = [
          'Bakytbekov Jakypbai',
          'Boobekov Dastan',
          'Kuralbekov Nurjigit',
          'Kyzdarbekov Nurdavlet',
        ]
        return (
          <>
            <div>
              <Header title="I love ReactJS" author="Caleb Park" />
              <Header title="I love NextJS" author="Samara" />
            </div>
            <div>
              <ul>
                {names.map((name, index) => (
                  <li key={index}> {name} </li>
                ))}
              </ul>
            </div>
          </>
        )
      }

      function Header({ title, author }) {
        console.log(title, author)
        return <h1> {author ? title : 'No Book Found by' + author}</h1>
      }

      const app = document.getElementById('root')
      ReactDOM.render(<HomePage />, app)
    </script>
  </body>
</html>

Incorporate interactivity with state using React Hooks. To add a button, you can include an HTML tag within your component. React needs to listen to events, such as clicks on a button, using event handlers.

To handle click events, pass in a property onClick to the button. Use Camel case for event names like onClick. Define a function, such as handleClick, above the return statement in your component to handle the click event. Pass this function to the onClick property.

To maintain data or state every time you click, React leverages Hooks. Hooks allow you to add logic, such as state, to your component. State is any information in your UI that changes over time.

Bring in the hook for state by accessing the React library with React.useState(). useState is a method that returns an array.

Destructure the state into values you want to create using array destructuring. The first element is the value of the state. The second element is a function to update the value, typically named with the prefix set, followed by what the state is (e.g., setLikes). You can set an initial value within the useState parameter, such as 0 for no likes. 19. Implement the update function (e.g., setLikes) in your handle click function to change the state of the likes, incrementing the value. Always use the setLikes function to update the state and avoid directly modifying the state to keep it immutable.

// index.html - After hooks and using State
<html>
  <body>
    <div id="root"></div>
    <script src="https://unpkg.com/react@17/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
    <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
    <script type="text/babel">
      function HomePage() {
        const [likes, setLikes]=React.useState(0)
        
        const names = [
          'Bakytbekov Jakypbai',
          'Boobekov Dastan',
          'Kuralbekov Nurjigit',
          'Kyzdarbekov Nurdavlet',
        ]
        
        function handleClick() {
           console.log("Increment Like count")
           setLikes(likes+1)
        }
        return (
          <>
            <div>
              <Header title="I love ReactJS" author="Caleb Park" />
              <Header title="I love NextJS" author="Samara" />
            </div>
            <div>
              <ul>
                {names.map((name, index) => (
                  <li key={index}> {name} </li>
                ))}
              </ul>
            </div>
            <button onClick ={handleClick} > Like : {likes} </button>
          </>
        )
      }

      function Header({ title, author }) {
        console.log(title, author)
        return <h1> {author ? title : 'No Book Found by' + author}</h1>
      }

      const app = document.getElementById('root')
      ReactDOM.render(<HomePage />, app)
    </script>
  </body>
</html>
PreviousLesson 3 - What is ReactJS - How it WorksNextLesson 4 - Create and Run a React Project with Vite - Full Overview

Last updated 3 months ago

Home Page Layout