Home > Software design >  How to make component inside a component?
How to make component inside a component?

Time:01-03

<Modal>
    <Modal.Footer>
        // any custom content. User can completely control behavior of this content. 
    </Modal.Footer>
</Modal>

export const ModalFooter = ({children}) => {
     return <div className={'modal-footer'}>{children}</div>
}

.modal-footer {
    // css to make footer sticky or scrollable. 
}

The scenario is that the footer of the Modal is going to be an optional feature. Only if the person sends <Modal.Footer/>, will that appear. So I want to create <Modal.Footer> inside the modal component. Can someone please tell me how to achieve that?

CodePudding user response:

create like this

const Modal = ({ children }) => <>{children}</>;

const ModalFooter = ({children}) => {
     return <div className={'modal-footer'}>{children}</div>
}

Modal.Footer = ModalFooter;
export default Modal;

CodePudding user response:

You can use the props.children property to create a component within a component. The props.children property in React is a special property that allows you to pass the content between a component's opening and closing tags when you use that component.

Here's an example of how the props.children property can be used to nest the ModalFooter component inside the Modal component:

import React from 'react';

export const Modal = ({ children }) => {
  return (
    <div className="modal">
      {children}
    </div>
  );
}

export const ModalFooter = ({ children }) => {
  return (
    <div className="modal-footer">
      {children}
    </div>
  );
}

.modal-footer {
  // css to make footer sticky or scrollable
}

Then, you can use the Modal and ModalFooter components like this:

<Modal>
  <Modal.Footer>
    // any custom content. User can completely control behavior of this content. 
  </Modal.Footer>
</Modal>

The ModalFooter component will be shown inside the Modal component, as will the content between the Modal. Footer tags will be provided to the ModalFooter component through the props.children property.

  • Related