DEV Community

Rakshambika
Rakshambika

Posted on

Props in React

Props (short for Properties) are one of the most important concepts in React. They allow us to pass data from a parent component to a child component, making components reusable and dynamic.

What are Props?

  • Props are read-only values passed to a component. They work similarly to function arguments in JavaScript.
  • Just as we pass values to a function, we can pass data to a React component using props.

Example

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

function App() {
  return <Welcome name="Raksha" />;
}
Enter fullscreen mode Exit fullscreen mode

Output

Hello, Raksha
Enter fullscreen mode Exit fullscreen mode

In the above example:

  • App is the parent component.
  • Welcome is the child component.
  • The value "Raksha" is passed as a prop named name.
  • The child component receives it through the props object.

Why Do We Use Props?

  • Reuse components with different data.
  • Pass information from parent to child components.
  • Make applications more dynamic and maintainable.
  • Avoid duplicating code.

Example

function Student(props) {
  return (
    <div>
      <h2>{props.name}</h2>
      <p>{props.course}</p>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode
function App() {
  return (
    <>
      <Student name="Raksha" course="Java Full Stack" />
      <Student name="Ranjan" course="React" />
    </>
  );
}
Enter fullscreen mode Exit fullscreen mode

The same component is reused with different data.


Top comments (0)