React.js

Props in react-js

Welcome readers, in this tutorial, we will understand how to use props in a react-js application.

1. Introduction

React is a flexible javascript library responsible for building reusable UI components. It is an open-source component-based frontend library responsible only for the view part of an application and works in a virtual document object model. But before that let us take a look at the differences between angular and react –

AngularReact
Complete frameworkLibrary
Object-oriented programmingExtension to the javascript library and its internal architecture is based on jsx
Based on the model view controller and real document object modelBased on the virtual document object model

1.1 Props in react-js

Props in react-js stand for properties. They are read-only objects that store the value of attributes of the tag and work similarly to the html attributes. Props are passed to the component and are immutable. They can be used to give any kind of data such as – string, array, integer, boolean, objects, or functions to the components.

1.2 Setting up dependencies

To play with react let us set up some of the required dependencies.

1.2.1 Setting up Node.js

To set up Node.js on windows you will need to download the installer from this link. Click on the installer (also include the NPM package manager) for your platform and run the installer to start with the Node.js setup wizard. Follow the wizard steps and click on Finish when it is done. If everything goes well you can navigate to the command prompt to verify if the installation was successful as shown in Fig. 1.

Fig. 1: Verifying node and npm installation
Fig. 1: Verifying node and npm installation

1.2.2 Setting up react-js project

Once the Nodejs setup is successful we will use the below command to install the react library and set up the project. Do note that the npx package is available with the npm 5.2 version and above.

Create project structure

$ npx create-react-app rendering-conditional-contect-reactjs-app

The above command will take some time to install the react library and create a new project named – rendering-conditional-contect-reactjs-app as shown below.

Fig. 2: Project structure of props-app
Fig. 2: Project structure of props-app

2. Props in react-js

To set up the application, we will need to navigate to a path where our project will reside and I will be using Visual Studio Code as my preferred IDE.

2.1 Setting up the react code

To understand a practical implementation let us go through some hands-on exercises.

2.1.1 Creating components

Create a folder named components in the src folder.

2.1.1.1 Create Got list component

Create a folder named list in the src/components folder and add the GotList.js file to it. The file will be responsible display the game of thrones characters’ names based on the selected house from the dropdown. The dropdown will be part of a separate component file.

GotList.js

import React from "react";

const GotList = (props) => {
  let characters = props.items;

  if (characters.length === 0) {
    return <h4>Found no character.</h4>;
  }

  return (
    <ul>
      {characters.map((item, idx) => (
        <li key={item.characterName}>{item.characterName}</li>
      ))}
    </ul>
  );
};

export default GotList;
2.1.1.2 Create Got filter component

Create a folder named filter in the src/components folder and add the GotFilter.js file to it. The file will be responsible for addressing the value change in the dropdown. A function is attached to the dropdown on-change trigger and will call the props.onChangeFilter method defined in the Got.js file as a tag.

GotFilter.js

import React from "react";

const GotFilter = (props) => {
  const dropdownChangeHandler = (event) => {
    let selectedHouse = event.target.value;
    props.onChangeFilter(selectedHouse);
  };

  return (
    <div>
      <label>Filter by house</label>
      <select value={props.selected} onChange={dropdownChangeHandler}>
        <option value="Lannister">Lannister</option>
        <option value="Targaryen">Targaryen</option>
        <option value="Stark">Stark</option>
        <option value="Baratheon">Baratheon</option>
      </select>
    </div>
  );
};

export default GotFilter;
2.1.1.3 Create Got component

Add a file named Got.js in the src/components folder and add the below code to it. The code acts as a parent component for a list and filter components.

Got.js

import React, { useState } from "react";
import GotFilter from "./filter/GotFilter";
import GotList from "./list/GotList";

const Got = (props) => {
  const characters = props.characters;

  const [filteredHouse, setFilteredHouse] = useState("Lannister");
  const filterChangeHandler = (house) => {
    setFilteredHouse(house);
  };

  const filteredCharacters = characters.filter((character) => {
    return character.houseName === filteredHouse;
  });

  return (
    <div>
      <GotFilter
        selected={filteredHouse}
        onChangeFilter={filterChangeHandler}
      ></GotFilter>
      <GotList items={filteredCharacters}></GotList>
    </div>
  );
};

export default Got;

2.1.2 Creating implementation file

In the App.js component we have used the react state to set the default value of the game of thrones list. We will pass the dummy list to the Got.js component.

App.js

import { useState } from "react";
import "./App.css";
import Got from "./components/got/Got";

const DUMMY_CHARACTERS = [
  {
    characterName: "Aegon Targaryen",
    houseName: "Targaryen"
  },
  {
    characterName: "Aerys II Targaryen",
    houseName: "Targaryen"
  },
  {
    characterName: "Alton Lannister",
    houseName: "Lannister"
  },
  {
    characterName: "Jaime Lannister",
    houseName: "Lannister"
  },
  {
    characterName: "Arya Stark",
    houseName: "Stark"
  },
  {
    characterName: "Maester Aemon",
    houseName: "Targaryen"
  }
];

function App() {
  const [characters, setCharacters] = useState(DUMMY_CHARACTERS);

  return (
    <div className="App">
      <h2>Props in reactjs</h2>
      <Got characters={characters}></Got>
    </div>
  );
}

export default App;

3. Run the setup

To run the application navigate to the project directory and enter the following command as shown below in the terminal.

Run command

$ npm run start

The application will be started on the default port. In case the application does not get started on the default port you can change the port number as per your requirement. I have changed the default port to 2000.

Fig. 3: props-app Application run
Fig. 3: props-app Application run

4. Demo

The application will be started in the default browser as shown below and the home page with a button will be shown.

Fig. 4: props-app Application demo
Fig. 4: props-app Application demo

Click on the dropdown to select the house name and the list will change. If no member is available for the house Found no character. message will be shown on the screen. That is all for this tutorial and I hope the article served you with whatever you were looking for. Happy Learning and do not forget to share!

5. Summary

In this tutorial, we created a react application and understood props in react-js. You can download the source code from the Downloads section.

6. Download the Project

This was a tutorial to understand props in a react application.

Download
You can download the full source code of this example here: Props in react-js

Yatin

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button