React

React โ€“ Components and Props

React-Components-and-Props

React is a popular JavaScript library for building user interfaces. One of the key features of React is the concept of components & props. In this blog, we will explore what components are, how to create and use them, and how to work with components & props in React.

Before reading this blog post, make sure to read the blog โ€œIntroduction to Reactโ€, which explains what React is and also provides a detailed step-by-step installation guide on React.

React Components

Components are the building blocks of a React application. They are reusable pieces of code that can be reused to create complex UIs. Components can contain HTML, CSS, and JavaScript code and can be nested within other components. The main idea behind components is to break down a complex UI into smaller, manageable pieces that can be easily managed and reused.

Components use two main concepts for managing data: props and state. Props are used to pass down the data from a parent component to a child component. The state is data that is managed within the component and can change based on user interactions or other events.

React components can also handle events, such as user interactions or form submissions, using event handlers. An event handler is a function that is passed as a prop to the component and is called in response to a specific event.

Components in React make it easier to create and manage complex UIs because they allow you to break down a complex UI into smaller, manageable pieces. They also make it easier to reuse UI code throughout your application. By using components, you can write more organized and maintainable code, and more easily create reusable UI elements.

Types of Components

There are two main types of components in React โ€“

  1. Functional components
  2. Class components.

Functional Components

Functional components are a simpler way to write React components in the form of JavaScript functions. They were introduced in React version 0.14 and are used to render a simple UI without the need for state or lifecycle methods.

A functional component takes in a set of props as its input and returns a React element that describes the UI to be rendered.

Letโ€™s understand this with an example.

Create a new React App with the name โ€œreact-components-tutorialโ€ by running the below command on the command prompt or terminal โ€“

npx create-react-app react-components-tutorial

If you are not aware of how to install and create a react app, follow this guided tutorial.

Jump to the folder โ€œreact-components-tutorialโ€ created after running the command and letโ€™s open it in visual studio code.

> cd react-components-tutorial
> code .

To understand the functional components, letโ€™s add a simple function component that will return a welcome message and introduce itself.

In visual studio code, open the app.js file and add the below javascript function to it.

function WelcomeMessage() {
  return <h1>Hello, Welcome! I am a Functional Component</h1>;
}

Now letโ€™s render this component in the App component. Update the function App in the App.js file.

function App() {
  return (
    <div className="App">
      <WelcomeMessage></WelcomeMessage>
    </div>
  );
}

Now, letโ€™s run the app. Open the terminal and run the command โ€“

 npm start

This will start the development server and run the app. This will also render our new functional component on UI.

As you can see above, we added a functional component, which returns a static string in the <h1> tag. We then called this component from the App component.

Functional components are great for simple UI elements that do not need to manage a state or handle complex lifecycle methods. They are also often easier to read and write than class components, making them a good choice for developers who are new to React.

However, for components that need to manage a state or interact with the React lifecycle, itโ€™s necessary to use a class component. Letโ€™s see next what are class components.

Class Components

Class components in React are JavaScript classes that extend the React.Component class. They allow for more complex logic and state management than functional components and are used for rendering a more complex UI.

Letโ€™s understand how to create class components using the same example we used for Functional components. Move to visual studio and create a new file in the src folder with the name WelcomeMessageClassComponent.js. Add the below code to it.

import React, { Component } from 'react';

class WelcomeMessageClassComponent extends Component {

  constructor(props) {
    super(props);    
  }  

  render() {
    return (
        <h1>Hello, Welcome! I am a Class Component</h1>
    );
  }
}

export default WelcomeMessageClassComponent;

Now open, App.js and update the App function with the below code โ€“

function App() {
  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <WelcomeMessageClassComponent></WelcomeMessageClassComponent>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
    </div>
  );
}

Now run the code by running the command npm start. This will render the new class component on UI.

In this example, the class componentโ€™s render method returns the UI, which consists of an h1 element displaying the welcome message.

Class components provide access to lifecycle methods, such as componentDidMount, componentDidUpdate, and componentWillUnmount, which allows for more complex logic and interactions with the DOM. They also allow for the use of a local state, which is used to store data that can change within the component.

Overall, class components are a good choice for components that require more complex logic or state management, while functional components are better suited for simple UI elements.

What are Props?

In React, props (short for properties) are data that are passed down from a parent component to its child components. Props are used to pass information from one component to another, allowing for more flexible and reusable code.

Letโ€™s understand props with an example. In the above section, we created components using functional and class which returns a static string in <h1> tag. Letโ€™s modify that code, to pass the data from the App function to the new component using props. We will also modify the new component to print the data received in props.

Open the file WelcomeMessageClassComponent.js and update the code as below โ€“

import React, { Component } from 'react';

class WelcomeMessageClassComponent extends Component {

  constructor(props) {
    super(props);    
  }  

  render() {
    return (
        <h1>Hello, Welcome {this.props.name}! I am a Class Component</h1>
    );
  }
}

export default WelcomeMessageClassComponent;

In this example, the WelcomeMessageClassComponent component takes in a name prop, which is displayed in an h1 element. The parent component can then pass in a value for the name prop when it renders the WelcomeMessageClassComponent component as shown below.

function App() {
  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <WelcomeMessageClassComponent name="Tech Artifacts"></WelcomeMessageClassComponent>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
    </div>
  );
}

Now letโ€™s run the code using the command npm start.

Props are passed to a component as an object and are available in the component as props in a functional component, or this.props in a class component. Props are read-only, meaning that they cannot be modified within the component.

Using props, you can create reusable components that can be used in different parts of your application with different data. This makes it easier to maintain and update your code and can result in more organized and efficient code.

Code Reference

You can find the code for this blog on GitHub.

Feel free to use and build upon the code for your own projects.

Conclusion

React Components and Props play a crucial role in building dynamic and reusable user interfaces in React. By breaking down complex UI into smaller, independent components, developers can easily manage and maintain their code.

Props, on the other hand, provide a way to pass data from parent components to child components, making the components more flexible and dynamic. Understanding how to work with React Components and Props is a fundamental aspect of React development.

Thank you for taking the time to read this blog post. We hope that you found the information provided in the blog to be helpful and informative. For similar content, please check out our other blogs.

We appreciate your support and feedback, and we would love to hear from you if you have any questions or comments about the blog. If you have any specific topic you want us to cover in the future, please feel free to let us know.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button