Home > Mobile >  how do I pass in dynamic data to my child component in react
how do I pass in dynamic data to my child component in react

Time:10-17

I'm trying to pass in a username and ID into my Support component like this:

  <HashRouter>
      <nav>
        <Link to="/">Home</Link>
        &nbsp;&nbsp;|&nbsp;&nbsp;
        <Link to="/profile">My Profile</Link>
        &nbsp;&nbsp;|&nbsp;&nbsp;
        <Link to="/vendor">Vendor Portal</Link>
        &nbsp;&nbsp;|&nbsp;&nbsp;
        <Link to="/help">Support</Link>
      </nav>
      <Routes>
        <Route exact path="/" element={<App />} />
        <Route exact path="/profile" element={<AuthComponent />} />
        <Route exact path="/help" element={<Support username={"jim"} id={"weenie"} /> }  />
      </Routes>
    </HashRouter>

and for support:

export class Support extends React.Component {
   render() {
    console.log(this.props)
  return (
    <div>
    <div>Support</div>
    <div>
        username?: {this.props.person['username']} <br/>
        User id?: {this.props.person.id}
        </div>
        </div>
    )
}
}

Support.propTypes = {
  username: PropTypes.string,
  id: PropTypes.string
}

I get white screen of death and somehow its called a couple times:

enter image description here

The props seem to be getting passed in so why is the propTypes breaking on it?

CodePudding user response:

Since you are passing username and id as props:

<Support username={"jim"} id={"weenie"} />

You can access them directly as this.props.username and this.props.id.

Also, you can pass strings in JSX directly as <Support username="jim" id="weenie" />

CodePudding user response:

You seem to be accessing the "person" property in props, which doesn't exist, and in the "person" you are again trying to read "username", hence the error "reading property username of undefined" because "person" is not there in props.

You will be good to go if you use "this.props.username" and "this.props.id"

  • Related