Props in React.js with Examples

Props in React.js with Examples

Props (short for "properties") in React are used to pass data from a parent component to a child component. They are read-only and help make components reusable.


1. Functional Component Example (Using Props)

In functional components, props are received as function parameters.(Arrow function)

Three.js

import React from 'react';

 

const Three = (props) =>

{

  return(<div>

    <h1>{props.name}</h1>

    <h1>{props.city}</h1>

  </div>)

 

}




export default Three;

 

App.js

 


import './App.css';

import Three from './components/Three';




function App() {

  return (

    <div className="App">

     

      <Three name="John" city="Kota"/>

     

 

    </div>

  );

}

 

export default App;

 

 

 

Function Component example Two

 

import React from "react";

 

function First(props)

{

  return(<div>

    <h1>{props.name}</h1>

    <h1>{props.age}</h1>

  </div>)

}

 

export default First

 

Explanation:

  • The Student component receives props and displays name and course.
  • The App component passes different values for name and course to different Student components.

2. Class Component Example (Using Props)

In class components, props are accessed via this.props.

import React, { Component } from "react";

 

import React, { Component } from "react";




class Sec extends Component

{

  render()

  {

    return(<div>

      <h1>{this.props.pageName}</h1>

      <p>{this.props.greet}</p>

    </div>)

  }

}

 

export default Sec;



Explanation:

  • In the Student class component, this.props.name and this.props.course are used to access the passed props.
  • The App component passes different props to different instances of the Student component.

Key Differences Between Functional and Class Components for Props

Feature

Functional Component

Class Component

Syntax

Uses function parameters

Uses this.props

Readability

More concise and easier to read

More verbose

State Management

Uses useState (Hooks)

Uses this.state

Performance

More performant as there is no this binding

Less performant due to this binding


Conclusion

  • Use functional components with props when possible, as they are simpler and preferred in modern React (with hooks).
  • Use class components only when working with legacy codebases.

 

Comments

Popular posts from this blog

Axios in React.js

Conditions in React.js

Applying map() Function in React.js (Arrays & Objects)