deepak chandrawanshi
deepak chandrawanshi

Reputation: 21

How to pass a component with props to another component as props in react

passing AgentDialogBox with prop reload to AgGridReactTable component

Upvotes: 1

Views: 8440

Answers (1)

user13937286
user13937286

Reputation:

Yes, you can pass a component as props to another component in various ways.

First way,

function Wrapper({button: Button}) {
  return (
    <div
      style={{
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
      }}
    >
      <Button />
    </div>
  );
}

export default function App() {
  const Button = () => {
    return <button onClick={() => console.log('button clicked')}>Click</button>;
  };

  // 👇️ pass button as props to the Wrapper component
  return (
    <div>
      <Wrapper button={Button} />
    </div>
  );
}

In the above example, a component is passed as a prop to a child component. The Wrapper component had to rename the prop from button to Button (capital first letter) because all component names must start with a capital letter.

Second Way,

function Wrapper({button}) {
  return (
    <div
      style={{
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
      }}
    >
      {button}
    </div>
  );
}

export default function App() {
  const Button = ({text}) => {
    return (
      <button onClick={() => console.log('button clicked')}>{text}</button>
    );
  };

  return (
    <div>
      <Wrapper button={<Button text="Some button text" />} />
    </div>
  );
}

In this example, we directly set the props of the Button component when passing it to the Wrapper component. We are not passing the actual component function, instead, we are passing the return value of the Button component. This means that we have to use the prop as {button}, instead of in our Wrapper component.

Now you can change your code using any of the above 2 mentioned ways, I'm using the second way here

const AgriReactTable = ({agentDetailsDialogBox, URL, columnDefs, reload}) => {

     return (
          <div>
              {agentDetailsDialogBox}
          </div>
     )
}


const App = () => {
      const [reload, setReload] = useState()
      const AgentDetailsDialogBox = () => { return <div>{someContent}</div>}
      
      return (
         <div>
             <AgriReactTable agentDetailsBox={<AgentDetailsBox reload={setReload} URL={apis.ADMIN_ALL_AGENT} columnDefs={columnDef} reload={reload}/>} />
         </div>
      )
}

Reference -> https://bobbyhadz.com/blog/react-pass-component-as-prop#:~:text=You%20can%20pass%20a%20component,assigned%20to%20the%20children%20prop.

Upvotes: 5

Related Questions