Home » Javascript » javascript – Disappearing of components while using react-router in React

javascript – Disappearing of components while using react-router in React

Posted by: admin February 24, 2020 Leave a comment

Questions:

so,I have been building a React application and I have been facing the similar problem of disappearing of component on refresh,more precisely its something with react router,I must be using it incorrectly

App.js look like

import React from "react";
import "./App.css";
import { Home } from "./components/home";

function App() {
 return <Home />;
}

export default App

Home Component

export class Home extends Component {
render() {
  return (
    <BrowserRouter>
      <NavigationBar />
      <Switch>
        <Route path="/jobPortal" component={JobPortal} />
      </Switch>
    </BrowserRouter>
  );
}

Common Navbar

const NavigationBar = ({ userType }) => {
  return (
    <Navbar style={globalStyles.container} bg="dark" variant="dark">
      <Navbar.Brand style={globalStyles.container} href="/">
        Soffice
      </Navbar.Brand>
      <Nav className="ml-auto">
        <Nav.Link as={NavLink} to="/JobPortal">
          Job Portal
        </Nav.Link>
        {userType && (
          <Nav.Link as={NavLink} to="/logout">
            Log Out
          </Nav.Link>
        )}

        {!userType && (
          <React.Fragment>
            <Nav.Link as={NavLink} to="/SignUp">
              Sign Up
            </Nav.Link>
            <Nav.Link as={NavLink} to="/SignIn">
              Sign In
            </Nav.Link>
          </React.Fragment>
        )}
      </Nav>
    </Navbar>
  );
};

export default NavigationBar;

Job Navbar which appears when we access jobPortal

const NavigationBar = ({ url }) => {
  // let {url,url} =useRouteMatch();
  console.log(url);
  return (
    <Navbar style={{ ...globalStyles.container }} bg="info" variant="dark">
      <Nav className="mx-auto">
        <Nav.Link style={styles.navBarColor} as={NavLink} to="/JobPortal">
          Home
        </Nav.Link>
        <Nav.Link style={styles.navBarColor} as={NavLink} to={`${url}/Post`}>
          Post Job
        </Nav.Link>
        <Nav.Link style={styles.navBarColor} as={NavLink} to={`${url}/Want`}>
          Want Job
        </Nav.Link>
        <Nav.Link style={styles.navBarColor} as={NavLink} to={`${url}/Contact`}>
          Contact
        </Nav.Link>
      </Nav>
    </Navbar>
  );
};
const styles = {
  navBarColor: {
    color: "white",
    fontSize: 22
  }
};
export default NavigationBar;

JobPortal component

export class JobPortal extends Component {
  componentDidMount() {
    console.log("path", this.props.match.url);
  }
  render() {
    const path = this.props.match.path;

    return (
      <BrowserRouter>
        <NavigationBar url={this.props.match.url} />
        <Switch>
          <Route path={`${path}/Want`} component={Want} />
        </Switch>
      </BrowserRouter>
    );
  }
}

Want component

class Want extends Component {
  constructor(props) {
    super(props);
    this.state = {
      name: "",
      email: "",
      message: "",
      jobs: [
        {
          jobId: 1,
          jobTitle: "software"
        }
      ]
    };
  }

  handleClick() {
    console.log(this.state);
  }
  componentWillMount() {
    this.url = this.props.location.pathname;
    console.log("location", this.props.location.pathname);
  }
  render() {
    const styles = {
      card: {
        width: "14em",
        height: "100%",
        fontSize: 20,
        padding: 10
      }
    };
    return (
      <BrowserRouter>
        <Route path={`${this.url}/:jobId`} component={Job} />
        <Container>
          <Container></Container>
          <Container>
            <Row>
              {this.state.jobs.map((job, index) => (
                <Col style={{ padding: 20 }}>
                  <Card text="white" bg="dark" style={styles.card}>
                    <Card.Body>
                      <Card.Title>
                        <Link to={`${this.url}/${job.jobId}`}>
                          {job.jobTitle}
                        </Link>
                      </Card.Title>
                    </Card.Body>
                  </Card>
                </Col>
              ))}
            </Row>
          </Container>
        </Container>
      </BrowserRouter>
    );
  }
}

export default Want;

Job component which is disappearing

export class Job extends Component {
  render() {
    return <p>this will disappear</p>;
  }
}

complete code sandbox link

https://codesandbox.io/s/mystifying-yalow-6jcyn?fontsize=14&hidenavigation=1&theme=dark

when I click on software link the card should disappear but it is not image
but so far the job component is appearing and working fine
but when I refresh the page, job component disappears and on clicking software link
its extending the url in a weird way.
component disappers

How to&Answers:

It’s happening because of this line in want.js

<Route path={`${this.props.location.pathname}/:jobId`} component={Job} />

Each time you reload the browser it adds the ID to the end of the pathname /JobPortal/Want/1 i.e /JobPortal/Want/1/1, /JobPortal/Want/1/1/1 so you are constantly changing the path that matches the route.

Just change it to

<Route path={`${this.props.match.path}/:jobId`} component={Job} />

I would also be more explicit with your link since it’s also duplicating itself onto the path on every click:

<Link to={`/JobPortal/Want/${job.jobId}`}>
 {job.jobTitle}
</Link>

Be careful when using this.props.location.pathname like this because it includes your params