DEV Community

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

Posted on

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.

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?