javascriptreactjscomponents

Pass additional props to functional component


I have a constellation like this:

<AComponent>
  foo={{bar: AFunctionalComponent}}
</AComponent>
export default function AFunctionalComponent({
  // These are props that will get passed "automatically" by 'AComponent'
  foo, 
  bar, 
  baz
}) 
{...}

Now I want to pass an additional prop to AFunctionalComponent. How do I do that?


Solution

  • I'm not sure, but I think you want to achieve something like this:

    import React from 'react';
    
    export function AFunctionComponent({myPropA, myPropB}){
      return <p>Hello myPropA: '{myPropA}', myPropB: '{myPropB}'</p>;
    }
    
    export function AComponent({Comp}){
      return <div>
        Component: <Comp myPropB="B from Component"/>
      </div>
    }
    
    export function App(props) {
      const ProxyComp = (proxyProps) => <AFunctionComponent {...proxyProps} myPropA="A from Proxy" />
      return (
        <div className='App'>
          <AComponent Comp={ProxyComp} />
        </div>
      );
    }
    

    By defining a 'Proxy'-Component, you can pass custom parameters.