DEV Community

Cover image for Passing props to component in react.
Aastha Pandey
Aastha Pandey

Posted on

2 1

Passing props to component in react.

In the below code, inside MyComponent I'm rendering Home component and also passing props count to it.

And then one can use count of MyComponent in Home component.
Home component is independent of MyComponent, any component can pass props to Home component.

import React, { useState } from "react";
export default function MyComponent() {
  const[count, setCount] = useState(0);

  return (
    <div>
      <Home count = {count}/> //passing props
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

The below code snippet is using the passed props, one can either destructure the object or accept the single props object.


import React from "react";
export default function Home({count}) {

  return (
    <div>
    {count}
    </div>
      );
}

Enter fullscreen mode Exit fullscreen mode

or


import React from "react";
export default function Home(props) {

  return (
    <div>
    {props.count}
    </div>
      );
}

Enter fullscreen mode Exit fullscreen mode

The Home component will only display 0 on-screen since I'm not updating the value of count.

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (2)

Collapse
 
sayf_a_cc723da8bec754a8cd profile image
Sayf A

epic tutorial! props in React are kind of like the properties you initialise under the init function of a class in python

Collapse
 
prakashmardi profile image
Prakash Mardi

Interested in crypto?

Cloudinary image

Video API: manage, encode, and optimize for any device, channel or network condition. Deliver branded video experiences in minutes and get deep engagement insights.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay