ReactJS - Props


In react Props is known as properties. Props are used to pass data from one component to another component in react usually from a parent to a child component. Props allow components to be dynamic and reusable by receiving values from their parent components. Inside the component, we can access the props passed from the parent, but we cannot change or modify them, as they are immutable.

Simple Example:

UserList.jsx (Child Component)
import React from 'react'

const UserList = (props) => {
  return (
    <div>
        <h2>Welcome  {props.name}</h2>
    </div>
  )
}

export default UserList;
App.jsx (Parent Component)
import React from 'react';
import UserList from './components/UserList';

function App() {

  return (
    <div>
      <UserList name="Sam"/>
      <UserList name="Ram"/>
    </div>
  );
}

export default App;

In this example:

  • The App component passes a prop called name with the value "Sam" to the UserList component.
  • UserList uses props.name to display the personalized message.
  • Reusing the same UserList component, but customizing its output by passing different values through props.

Output:

props

Passing Multiple Props Example:

UserList.jsx (Child Component)
import React from 'react'

const UserList = (props) => {
  return (
    <div>
        <p>Name : {props.name}</p>
        <p>Age : {props.age}</p>
        <p>City : {props.city}</p>
    </div>
  )
}

export default UserList;
App.jsx (Parent Component)
import React from 'react';
import UserList from './components/UserList';

function App() {

  return (
    <div>
      <UserList name="Sam" age={25} city="Salem" /><hr/>
      <UserList name="Ram" age={32} city="Chennai" /><hr/>
      <UserList name="Sara" age={27} city="Coimbatore" /><hr/>
    </div>
  );
}

export default App;

In this example:

  • The UserList component expects three props: name , age and city
  • In App.jsx we're passing three props (name , age and city) to the UserList component. Each <UserList/> is customized with different values.

Output:

props

Using Default Props Example:

Default props are values that a component will use if no prop value is provided by the parent. They help prevent errors and provide fallback behavior.

UserList.jsx (Child Component)
import React from 'react';

const UserList = ({ name = "Guest User" }) => {
  return (
    <div>
      <h2>Welcome {name}</h2>
    </div>
  );
};

export default UserList;
App.jsx (Parent Component)
import React from 'react';
import UserList from './components/UserList';

function App() {

  return (
    <div>
      <UserList />
      <UserList name="Sam" />
    </div>
  );
}

export default App;

Output:

Default props