DEV Community

Cover image for React Props: Passing Data Between Components
Ezhil Abinaya K
Ezhil Abinaya K

Posted on

React Props: Passing Data Between Components

React Props
Props are arguments passed into React components.Props are passed to components via HTML attributes.props stands for properties.
The component receives the argument as a props object:

import { createRoot } from 'react-dom/client'

function Car(props) {
  return (
    <h2>I am a {props.brand}!</h2>
  );
}

createRoot(document.getElementById('root')).render(
  <Car brand="Ford" />
);
//I am a Ford!
Enter fullscreen mode Exit fullscreen mode

You can use myobj instead of props in the component:

import { createRoot } from 'react-dom/client'

function Car(myobj) {
  return (
    <h2>I am a {myobj.brand}!</h2>
  );
}

createRoot(document.getElementById('root')).render(
  <Car brand="Ford" />
);
//I am a Ford!
Enter fullscreen mode Exit fullscreen mode
function App() {
  return <Greeting name="Alice" />;
}

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

export default App;
//Hello, Alice!
Enter fullscreen mode Exit fullscreen mode

props obj
Parent Component (App.jsx)

function App() {
  return <Student name="Ezhil" age={22} city="Chennai" />;
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Child Component (Student.jsx)

function Student(props) {
  console.log(props);

  return (
    <>
      <h2>Name: {props.name}</h2>
      <h2>Age: {props.age}</h2>
      <h2>City: {props.city}</h2>
    </>
  );
}

export default Student;
//Name: Ezhil
Age: 22
City: Chennai
Enter fullscreen mode Exit fullscreen mode

Passing an Array as Props
Parent

function App() {
  const fruits = ["Apple", "Mango", "Orange"];

  return <FruitList fruits={fruits} />;
}
Enter fullscreen mode Exit fullscreen mode

Child

function FruitList(props) {
  console.log(props);

  return <h1>{props.fruits[0]}</h1>;
}
//Apple
Enter fullscreen mode Exit fullscreen mode
function FruitList(props) {
  return (
    <>
      {props.fruits.map((fruit) => (
        <h2>{fruit}</h2>
      ))}
    </>
  );
}
//Apple
Mango
Orange
Enter fullscreen mode Exit fullscreen mode

Reference
https://www.w3schools.com/react/react_props.asp

Top comments (0)