Search code examples
javascriptreactjsreact-hooksreact-propsreact-component

How to pass props from parent to child in react?


I've been refactoring a small application that was initially within one file into it's own separate components. Currently I have a child component UsersTable that I am rendering within the parent Users2. I am passing some dummy data from the parent as props to the child but am getting the lovely Cannot read property 'map' of undefined.

I am using react hooks and passing props with the spread operator in the parent:

<UsersTable {...columns} {...data} />

And the child is receiving that here:

    export const UsersTable = props => {
  const [usersState, setUsersState] = useState(props)

  useEffect(() => {
    setUsersState(props)
  }, [props])

  const renderUsers = () => {
    if (usersState) {
      return usersState.map(d => items(d))
    } else {
      return noData
    }
  }

As well as down in the return function here:

<ActionList columns={usersState}>{renderUsers}</ActionList>

I am specifically trying to figure out why the data prop (an array of objects), is returning undefined. Linking my sandbox here. I wondering if the issue is perhaps related to passing multiple separate props via spread operators.

Any help or advice around what I am trying to accomplish would be much appreciated!


Solution

  • That's not a correct way to pass down props.

    Props are passed as properties of an object and hence you need to define a name and value to it.

    For ex, you need to write,

    <UsersTable {...columns} {...data} /> 
    

    as

    <UsersTable columns={columns} data = {data} />
    

    Now the UserTable component will get this props object,

    props = { 
    columns=the column data,
    data = the data
    }
    

    To use this props, you can use destructuring

    const {data, columns} = props;
    

    or you can use the dot notation, props.column & props.data