Search code examples
javascriptreactjsreact-routerreact-bootstrap

Item appearing below current page content, want it to be floating window


I am using React. I have 2 class components:

  1. MyPage
  2. NewComponent (path: /api/pages/components/new)

Here is my NewComponent class:

import React from 'react';
import { Modal } from 'react-bootstrap';


class NewComponent extends React.Component{

    constructor(props){
        super(props);
    }
    

    render(){
        return(
              <Modal.Dialog>
                    <Modal.Header>
                        <Modal.Title>New Component</Modal.Title>
                         </Modal.Header>
                </Modal.Dialog>

        );
    }
}

export default NewComponent;

Here is my Page class:

import React from 'react';
import { BrowserRouter as Router, NavLink, Route} from 'react-router-dom';
import { Button } from 'react-bootstrap';


class MyPage extends React.Component{

    constructor(props){
        super(props);
    }
    

    render(){
        return(
        
            {/**   some code .... */}
            
              <div className="d-block mb-4 mb-md-0">
                <Router>

                    <NavLink to={Routes.NewComponentForm.path}>
                        <Button id="addComponent" className="btn btn-dark rounded-circle btn-lg" >+</Button>
                         <Route path="/api/pages/components/new" component={NewComponentForm}/>
                    </NavLink>
                </Router>
               </div>
        );
    }
    
}

export default MyPage;

My Question:

The items of the NewComponent class are rendered on the same page below the items of the MyPage class.

What I want is to have the Modal component (NewComponent class) to be a floating window.


Solution

  • My first thought was that you hadn't imported the the stylesheet from react-bootstrap into your project.

    But it's actually a problem with your react-router-dom setup.

    You want to have one Router component at the outermost level of your app. You can have multiple blocks of Routes in the same Router. Unless you are doing something complex with nested routes you probably only have one set of Route components which go inside a Switch statement in your App.

    export default function App() {
      return (
        <Router>
          <Switch>
            <Route path={Routes.NewComponentForm.path} component={NewComponentForm} />
            <Route component={MyPage} />
          </Switch>
        </Router>
      );
    }
    

    in MyPage

    return(
      {/**   some code .... */}
      <div className="d-block mb-4 mb-md-0">
        <NavLink to={Routes.NewComponentForm.path}>
          <Button id="addComponent" className="btn btn-dark rounded-circle btn-lg" >+</Button>
        </NavLink>
      </div>
    );
    

    I'm confused about the relationship between NewComponent and NewComponentForm. Here I am assuming that the route with the form renders the modal.