React notes - 03 Components

React notes - 03 Components

This is brief visualization of the chapter about components:

In React, a component is a building block of the user interface. It can be a function or a class that receives inputs called props and returns a hierarchy of views that represent the UI.

In our application, we have a default component App let’s run our application, previously just a little bit clean our project:

  • delete public folder, assets folder, vite file, index.css file;

  • remove all unnecessary imports from App.tsx file and code from App.css file;

  • and in App.tsx file only left this code:

      import './App.css'
    
      function App() {
        return (
          <h1>Hello from default component App.</h1>
        )
      }
    
      export default App
    

Run our application npm run dev and open it in the browser:

Screenshot 2023-03-12 at 20.51.23.png

And what we get:

  • in our index.html file, we have <div id="root"></div> - this is our root entry point for UI;

  • in main.tsx file we see the code:

      ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(
        <React.StrictMode>
          <App />
        </React.StrictMode>,
      )
    

    This tells us that we searching for an element with id=root and .render in this element our component App.

  • then let’s check our App.tsx file:

      function App() {
        return (
          <h1>Hello from default component App.</h1>
        )
      }
    
      export default App
    

    Here we have a simple functional component App that returns jsx with h1 element.

  • And now let’s inspect what we have in our HTML:

    Screenshot 2023-03-12 at 21.05.57.png

    All is like we expect, we have div#root in which we insert our h1 with text.

Summary

Here we saw an example of a functional React component and how to React works from a code side and for a basic understanding of how it works in UI. More understandable it will be when we will add more pages and will this SPA is in action.

And a couple of words about Class Components. In modern React applications they just don’t use it, even official React documentation told that they switched to functional components. So, don’t see a reason to describe them, maybe only in situations when you will work, for some reason, with a very old React application you can meet Class Components in any other situation better to start using Functional Components.

Previous note - Let’s run our application

Next note - Component Basics