DEV Community

loading...
Cover image for Passing props to component in react.

Passing props to component in react.

Aastha Pandey
I write only on those topics, wherein I myself was stuck at some point in time.
・1 min read

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.

Discussion (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?