Yogesh Chauhan's Blog

Components and Props in React

in React on April 25, 2021

As we have already seen in the React Basics, components are small chunk of code like functions. They are reusable and helps to manage the UI easily.

Components accepts inputs called props (properties).

Just like functions, components also return some value. In React, they return Ract elements that defines the UI. On a side note, JSX helps in overall UI creation.

Function Components

Function components are defined like JavaScript functions and that’s why they are called function components.

For e.g.

function Greet(props) {
  return <h1>Hello, {props.name}</h1>;

The function component above accepts one single argument called props.

Class Components

Class components are created using ES6 class syntax.

For e.g.

class Greet extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}</h1>;

Rendering the component

We saw how to create and render elements earlier.

The same way we can create React elements to represent components.

Just like this:

const element = <Greet name="Yogesh" />;

React will create a single object containing the JSX attributes and children. That single object is called props in React.

Checkout the working demo:

When we call ReactDOM with Greet name=”Yogesh”, React calls Greet component and passed the props object. The props object has {name: ‘Yogesh’} inside it. That’s how our Greet component access the name inside the object, using the famous JavaScript dot operator. And then it simply renders it.

How does React differentiate the DOM tags and components tags?

React checks the first letter of the tag and if it’s in lowercase the it considers that as a DOM tag otherwise it’ll treat as components.

Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#Aug 15 Is PHP still good for back-end programming? #Aug 10 How to create a multisite network in WordPress? #Aug 3 How to create a circle that follows a cursor using JavaScript and CSS? #Aug 3 How to make a curtain slider using jQuery and CSS? #Aug 2 How to progressively load images and add a blurry placeholder? #Aug 1 How to create a placeholder loader (throbber) using CSS?
You might also like these
How SCSS (Sass) finds a module without a file extension?SCSSPHP Login System using PDO Part 1: Create User Registration PagePHPModules and its Core features in JavaScriptJavaScriptArray destructuring and Object destructuring in JavaScriptJavaScriptHow to define visibility for a property in PHP?PHPHow to add CurrencyPipe in TypeScript file in Angular 9 Project?Angular