Search code examples
javascriptreactjscomponents

ReactJs component structure - Form inside modal


I am using the react-bootstrap Modal, Form and Button.

Desiring the functionality of clicking the button should open the modal with a form inside it. After filling out the form, one clicks a button (on the modal) and it validates the form data and posts it through a REST API.

I got far enough to figure out that my component split should be as follows:

A button component, a modal component and a form component.

What would be the correct way to structure these components in terms of props/state and placing the functions for validating the data? I am having trouble in understanding the child/parent relationship and when it's applicable


Solution

  • Components:

    1. App Component: This is going to be the top level component

    2. Button Component (If its just a button can also be just a button): If this is just a button you can keep this has a just a button in App component, if you are willing to reuse this with some custom element place it in a component.

    3. Modal component: This is going to hold your modal like header,body,footer
    4. Form component: This is a component which will hold the form and its validations.

    Component Tree:

    App Component will contain a state like showModal, we need to have a handler to set this value and this handler gets triggered when the button is clicked.

    import FormModal from './FormModal';   
    
    class App extends React.Component {
       state = {
        showModal : false
      }
    
      showModalHandler = (event) =>{
        this.setState({showModal:true});
      }
    
      hideModalHandler = (event) =>{
        this.setState({showModal:false});
      }
    
      render() {
        return (
          <div className="shopping-list">
            <button type="button" onClick={this.showModalHandler}>Click Me! 
            </button>
          </div>
          <FormModal showModal={this.sate.showModal} hideModalHandler={this.hideModalHandler}></FormModal>
        );
      }
    }
    

    Form Modal:

    import FormContent from './FormContent';
    
    class FormModal extends React.Component {
      render() {
        const formContent = <FormContent></FormContent>;
        const modal = this.props.showModal ? <div>{formContent}</div> : null;
        return (
          <div>
            {modal}
          </div>
        );
      }
    }
    
    export default FormModal;
    

    Hope that helped!