The Basics Of React Components

The Basics Of React Components

Understanding React Components: Building Blocks of Dynamic Web Apps

In an ever improving world of Web development, React framework is one of the best frameworks for developing dynamic and interactive web applications. There is a fundamental concept at the heart of React: components. This serves as the foundation of every React application, which makes it easy for developers to build reusable and manageable code.

This guide is meant for both experienced developers who want to learn more and beginners who want to understand the fundamentals of React. Join me as we go through this insightful journey where we'll explore what components are, how they work, and why they are essential in crafting modern web applications.

Prerequisites

To fully understand this article, you must have basic knowledge of

  • JavaScript

  • React

What Is A React Component?

A React component is the fundamental building block of a React application. It is a reusable piece of code that carries out a specific function or view. Components can be thought of as different units of code that come together to create a user interface (UI).

Two Things To Note About React Components

  1. The name of a component must be capitalized, i.e. ComponentExample and not componentExample.

  2. A React component must return JSX (a syntax extension to JavaScript). It looks just like HTML but is different in syntax.

There Are Two Types Of React Components

  1. Functional Components: These are functions that accept input properties (conventionally called "props" in React) and return JSX (JavaScript XML) to describe the UI. Functional components are typically used for simpler UI elements.

    Here's an example of what functional components look like:

     function Welcome(props) {
       return <h1>Hello, {props.name}</h1>;
     }
     //You can also use arrow function
     const Welcome = (props) => {
         return <h1>Hello, {props.name} </h1>
     }
    
  2. Class Components: These are classes that extend the React.Component class. They have the ability to manage component state, handle lifecycle methods, and are used for more complex UI elements.

    Here’s an example of class component code:

     class Counter extends React.Component {
       constructor(props) {
         super(props);
       }
       render() {
         return (
           <div>
             <p>Hey there</p>
           </div>
         );
       }
     }
    

Some Key Things To Know About React Components

  • Data can be passed through props. Data can be passed to our components through customized attributes. We can use whatever name for these attributes as long as it doesn’t coincide with already existing attribute names in JSX. Examples of those already existing attribute names are className, styles, onClick, etc. For this to work, the attribute name is the key to accessing the value it holds.

    Here’s an example of how it works:

      import React from 'react';
      import ReactDOM from 'react-dom';
    
      // MyComponent that receives data through props
      function MyComponent(props) {
        return (
          <div>
            <h1>Hello, {props.name}!</h1>
            <p>Your age is {props.age}.</p>
          </div>
        );
      }
    
      // App component where data is defined and passed as props to MyComponent
      function App() {
        // Define data to be passed as props
        const name = 'John';
        const age = 30;
    
        return (
          <div>
            {/* Pass data as props to MyComponent */}
            <MyComponent name={name} age={age} />
          </div>
        );
      }
    
      // Render the App component
      ReactDOM.render(<App />, document.getElementById('root'));
    

    In this example, the base component which is App component defines data that it passes down to MyComponent as props. The code sample seen in MyComponent is what displays on the user interface for the user to interact with. This way, we can diversify the data rendered on the UI.

    In order to render the same data on the UI without using props, we can do what we call ‘destructuring’, by using curly braces({ }).

      // MyComponent that receives data by destructuring
      function MyComponent({name, age}) {
        return (
          <div>
            <h1>Hello, {name}!</h1>
            <p>Your age is {age}.</p>
          </div>
        );
      }
    

    Whatever is a JavaScript value can be passed through props, including arrays, objects, other elements, and components.

  • Children prop is available. Whatever attribute is between the opening and closing tags of a component is passed to that component as 'children'.

    Here’s an example to make you understand better:

      import React from 'react';
    
      // A simple component that wraps its children with a <div> element
      const WrapperComponent = ({ children }) => {
        return (
          <div className="wrapper">
            {children}
          </div>
        );
      };
    
      // Usage of the WrapperComponent with children
      const App = () => {
        return (
          <div>
            <h1>Hello, world!</h1>
            <WrapperComponent>
              <p>This is a paragraph inside the wrapper.</p>
              <button>Click me</button>
            </WrapperComponent>
          </div>
        );
      };
    
      export default App;
    

    You can see in the code that children was passed to the Wrapper component and then Wrapper was passed to the App component with a p tag and button feature inside of it.. Because children has been passed to the Wrapper, the App component immediately recognizes the features inside of it and displays it to the user.

  • Conditional rendering can be done. Our components are written in JSX, which is also JavaScript, so we can set a condition that determines the features that are rendered to the user interface.

      const Greeting = ({small}) => {
          if(small) {
              return <h1> Hello Small World! </h1>
          }
          return <h1> Hello Big World! </h1>
      }
    
      const App = () => {
          return (
              <div>
                  <Greeting small={true}/> //Hello Small World! 
                  <Greeting small={false}/> // Hello Big World!
              </div>
          )
      }
    

    A ternary operator can also be used for conditional rendering

      const Greeting = ({small}) => {
          return( small ? <h1> Hello Small World! </h1> : <h1> Hello Big World! </h1>)
      }
    
      const App = () => {
          return (
              <div>
                  <Greeting small={true}/> // Hello Small World!
                  <Greeting small={false}/> // Hello Big World!
              </div>
          )
      }
    
  • Returning null renders nothing on the Document Object Model ( DOM )

      const Greeting = ({small}) => {
          return( small ? <h1> Hello Small World! </h1> : null)
      }
    
      const App = () => {
          return (
              <div>
                  <Greeting small={true}/> //Hello Small World!
                  <Greeting small={false}/> // This renders nothing
              </div>
          )
      }
    

Conclusion

When developing a web application with React, components serve as the building blocks. They help manipulate the DOM and form the entirety of the user interface. One main usefulness of components is their reusability; you get to reuse whatever component you need as many times as you want on any part of your application. This helps to simplify development, improve the maintainability of code, and facilitate the scalability of React applications.

Now you have a chance to take advantage of this knowledge and make it work. You play with it a little bit, and little by little, you get used to it. Believe me, when developing web applications, it's very nice to use React.

Happy coding!