0

How to pass id from one component to another component in react in functional component?

this.props doesn't work for my functional component?

  1. Parent component
<Link to={{
      pathname: '/details',
      state: {id: 1, name: 'sabaoon', shirt: 'green'}
    }}>
Learn More
</Link>

2.Child Component

 {props.location.state.name}
Aswath
  • 811
  • 7
  • 20
Siddarth
  • 49
  • 3
  • 6
  • Does this help (https://stackoverflow.com/questions/22639534/pass-props-to-parent-component-in-react-js?rq=1) ? – Aswath Feb 22 '22 at 06:04

2 Answers2

0

You can pass id by props from one component to another. If you are using functional Component then:

import React from 'react'

const Parent = () => {
  return (
    <Child id={'test_123'}/>
  )
}

And in Child Component you can de-structure id from props like that:

const Child = ({id}) => {
  return (
    <div>
      <h1>{id}</h1>
    </div>
  )
}
Asad Haroon
  • 476
  • 3
  • 9
0

You can have a props argument in the declaration of your functional child component, from where you can get values passed from the parent component.

//Parent Functional Component
function Parent(){
  var id = 1 //some variable or object that you want to pass to the child
  var names = {
    1: "A",
    2: "B",
    3: "C"
  }

  return (
    <>
      <div>This is a parent component!</div>
      <Child currId={id} names={names} />
    </>
  )
}

//Child Functional component
function Child(props){
  return (
    <div> Hello, {props.names[props.currId]}! </div>
  )
}

The result will look something like this,

This is a parent component!
Hello, A!

More details can be found in this documentation.

Jay Shukla
  • 454
  • 4
  • 13