Prop syntax for how to use custom component Props, inside another custom component?

280 Views Asked by At

Hopefully, I can explain this correctly.

I have a custom Button component in a React app and this component has props like disabled, size etc. This custom Button component is then imported to a Modal component.

Sometimes, while inside the Modal component, I want to access the props that exist inside the Button component to modify each Modal. For example in one Modal, I might want a button to be disabled but in other modals, I don't.

So I create a prop inside Modal called buttonAddionalProps and make it hold the value of ButtonProps (this is written in a types/props file in typescript).

Now, back to the Modal, I want to pass the prop buttonAdditionalProps to my Modal but I am not sure what the syntax would be.

Example:

<Modal
   id="123"
   primaryAction={handleClose}
   buttonAddionalProp= " What would this be? "
></Modal> 

Everything I have tried doesn't work and all my google searches aren't leading me down the right path.

// 2 examples of things I tried to help show what I am trying to do

buttonAddionalProp = {Button={disabled = {true}}  -- fail 
buttonAddionalProp = {Button={disabled}}          -- fail 
1

There are 1 best solutions below

2
AltDan On

To pass the props from your Modal component to the Button component, you can use the spread operator (...) in JSX. This will spread the additional props to your Button component, allowing you to access and modify them as needed.

<Modal
  id="123"
  primaryAction={handleClose}
  buttonAdditionalProps={{ ...ButtonProps, disabled: true }}
></Modal>

Alternatively you can pass the button as a child and modify directly:

<Modal
  id="123"
  primaryAction={handleClose}>
 <Button disabled />
</Modal>

This can then be rendered in the modal component using the children prop.