Search code examples
javascriptreactjsreact-props

Pass prop that has a dynamic name in react to child component


If I have a prop that has a dynamic name, say myProp[regNo] where regNo could be a series of numbers, (in the react Dev tools, it could render as myProp5645262 how do I pass that prop to a child?


Solution

  • You can access that through this.props or props depending on if you are using class components or hooks.

    Use Object.keys(props) to get the list of property names. Then you will be able to access the property.

    This is a dummy example using hooks.

    const MyComponent = (props) => {
      const keys = Object.keys(props); // ['myProp12345', 'myProp23456', 'apple']
      const myProps = keys.filter(name => name.startsWith('myProp')) // ['myProp12345', 'myProp23456']
    
      // Do whatever you want here to map your values
    
      const myValues = myProps.map(propName => ({
        name: propName,
        value: props[propName]
      })) // [{ name: 'myProp12345', value: 'a' }, { name: 'myProp23456', value: 'b' }]
      
    
      return (
        <Child myValues={myValues} />
      )
    }
    
    // ...
    
    <MyComponent myProp12345='a' myProp23456='b' apple='c' />
    

    EDIT: After reading your question again, it seems like you wanted to pass these props to your children as is. If so:

    const MyComponent = (props) => {
      const keys = Object.keys(props); // ['myProp12345', 'myProp23456', 'apple']
      const myPropsMap = keys.reduce((map, key) => ({
        ...map,
        [key]: props[key]
      }), {}) // {myProp12345: 'a', myProp23456: 'b'}
    
      // Here both of the myPropXXX are passed to this child.
      return (
        <Child {...myPropsMap} />
      )
    }
    
    // ...
    
    <MyComponent myProp12345='a' myProp23456='b' apple='c' />