React-router-dom rendering component on the same page - javascript

i am using react-router-dom in my project when i am proving routes instead of rendering the component in another page dom rendering component in the same page below my first component
My App.js
import React,{Component} from 'react';
import './App.css'
import Layout from './components/front/layout'
import FirstPage from './components/index/firstpage';
import {BrowserRouter ,Switch,Route} from 'react-router-dom';
class App extends Component {
render(){
return (
<div className="container">
<BrowserRouter>
<FirstPage/>
<Switch>
<Route path='/Layout' exact component={Layout} />
</Switch>
</BrowserRouter>
</div>
);
}
}
export default App;
My another middlePortion.js where i am using imported from react-router-dom to route to another page
import React from 'react';
import { Button, Form } from 'reactstrap';
import axios from 'axios';
import '../../css/style.css'
import {Link} from 'react-router-dom'
class Middleportion extends React.Component {
constructor(props){
super(props);
this.Submit = this.Submit.bind(this);
}
render() {
const layStyle={
color:'white'
};
return (
<div className='row frnt'>
<div className="col-md-3">
</div>
<div className="col-md-6 am ">
<div className="row align-items-center">
<div className="row justify-content-center bg-primary pp">
<ul className="list-unstyled">
<li><Link style={layStyle} to='/Layout'>
male
</Link></li>
</ul>
</div>
</div>
</div>
<div className="col-md-3">
</div>
</div>
);
}
}
export default Middleportion;
I want to render my Layout component on separate page but its rendering on the same page please help me out

The problem with your code is that you're rendering FirstPage manually as if to be hard coded.
In order to get FirstPage and Layout to render in separate routes, you need to create a separate route inside your <Switch> and use FirstPage as the component prop like you did with Layout.
It would look like this:
(
<div className="container">
<BrowserRouter>
<Switch>
<Route exact path='/' component={FirstPage} />
<Route exact path='/Layout' component={Layout} />
</Switch>
</BrowserRouter>
</div>
)
With the setup above, the FirstPage component would render only on the / route and the Layout component would only render on the /layout route.

Related

React Router - Why is the switch not changing html when the path changes?

I am working on a web app, and i am having some issues with reactJS Router. When i redirect to the /sell path the HTML form the / path stays, and the HTML inside the /sell route doesn't load.
Am i doing something wrong? would anyone be able to point me towards the right direction?
import React, { Component } from "react";
import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom";
import Helmet from "react-helmet";
import CreateList from "./CreateList";
//https://colorhunt.co/palette/33990
//https://colorhunt.co/palette/66990
class Home extends Component {
constructor(props) {
super(props);
this.state = { appTitle: "better craigslist"};
}
render() {
return (
<React.Fragment>
<Helmet>
<title>{this.state.appTitle}</title>
</Helmet>
<Router>
<Switch>
<Route path="/">
<div id="header-text">
<h1 className="center-align">
<b>Sellify</b>
</h1>
<h5 className="center-align">
Need to get rid of your stuff? create a listing and sell it here! <br /> Looking for something? Check if its on selify!
</h5>
</div>
<div className="col s12 center">
<Router>
<Link to="/sell">
<button className="btn" id="create-listing-button">
Create Listing
</button>
</Link>
</Router>
</div>
</Route>
<Route path="/sell">
<h1>Test</h1>
</Route>
</Switch>
</Router>
</React.Fragment>
);
}
}
export default Home;
Thank you very much!
Issue
You've more than one Router. The inner Router context is handling the links so the outer Router isn't notified.
Solution
Use only one Router component, remove the Router around the Link. Additionally, when using a Switch, path order and specificity matter. You want to oder your more specific paths before less specific paths. "/" is a path prefix for all paths and would be matched and rendered before "/sell".
class Home extends Component {
constructor(props) {
super(props);
this.state = { appTitle: "better craigslist" };
}
render() {
return (
<React.Fragment>
<Helmet>
<title>{this.state.appTitle}</title>
</Helmet>
<Router>
<Switch>
<Route path="/sell">
<h1>Test</h1>
</Route>
<Route path="/">
...
<div className="col s12 center">
<Link to="/sell">
<button className="btn" id="create-listing-button">
Create Listing
</button>
</Link>
</div>
</Route>
</Switch>
</Router>
</React.Fragment>
);
}
}

ReactJS router doesn't load components unless I refresh the page

ReactJS router doesn't load the component in different route unless I refresh , even though I've created a different project with same installations and It does work properly, but in my current project it doesn't.
App.js
import React, {Component} from 'react';
import { BrowserRouter, Route, Switch} from 'react-router-dom';
import Navigation from './components/Navigation'
import Home from './components/Home'
import Blogs from './components/Blogs'
import Footer from './components/Footer'
import Services from './components/Services'
class App extends Component {
render(){
return (
<BrowserRouter>
<div className='grid-container'>
<Navigation />
<div className='content'>
<Route path='/blogs' component={Blogs} />
<Route path='/' component={Home} exact/>
<Route path='/' component={Services}/>
</div>
<Footer />
</div>
</BrowserRouter>
);
}
}
export default App;
Home.js
import React from 'react';
import {Link, BrowserRouter} from 'react-router-dom'
const Home = () => {
return (
<BrowserRouter>
<section className="carousel-section-wrapper home">
<div className="carousel-inner">
<div className="carousel-section carousel-item active clip-bg pt-225 pb-200 img-bg">
<div className="container">
<div className="row">
<div className="col-xl-8 col-lg-10 mx-auto">
<div className="carousel-content text-center">
<div className="section-title">
<h2>test content</h2>
<p className="text-white">test content</p>
</div>
<Link to="/blogs" className="theme-btn">Read My Blogs</Link>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
</BrowserRouter>
)
}
export default Home
Blogs.js
import React from 'react';
const Blogs = () => {
return (
<h1>Blogs</h1>
)
}
export default Blogs
Expected result: componetns home and services disappear, and blogs component appear when I click to any button redirects to /blogs
Actual result: the state of the page stays the same unless I refresh the browser
your help would be appreciated.
You've used BrowserRouter in nested components, in your App and Home components and it won't work this way. To fix this, you only must have the BrowserRouter in the App component.

How to use router for switching between components with a key value pair in react

I am just stuck on this router concept. I am pretty new to react. SO I think we also have a better way of doing so. Correct me if I am doing these things wrong or if we have a better option.
This is my App.js
import React from 'react';
import './App.css';
import Header from './Header';
import Profile from './Profile';
import {BrowserRouter as Router, Switch, Route} from "react-router-dom";
import PullRequests from './PullRequests';
import Overview from "./Overview";
import Repo from './Repo';
function App() {
return (
<Router>
<div className="App">
<Header />
<Switch>
<Route path="/">
<Profile template= {<Overview/>} />
</Route>
<Route path="/tagname=Repo">
<Profile template= {<Repo/>} />
</Route>
<Route path="/Pullrequests">
<PullRequests />
</Route>
</Switch>
</div>
</Router>
);
}
export default App;
This is my profile.js
import React from 'react'
import "./Profile.css"
import { Avatar} from '#material-ui/core';
import PeopleAltIcon from '#material-ui/icons/PeopleAlt';
import StarBorderIcon from '#material-ui/icons/StarBorder';
import LocationOnIcon from '#material-ui/icons/LocationOn';
import Underlinenav from './Underlinenav';
function Profile({template}) {
return (
<div className="profile">
<div className="profile__left">
<Avatar src="https://avatars0.githubusercontent.com/u/68982304?s=460&u=6b37f00eb36173e0f5f5bc04db9e63066d408d80&v=4" className="profile__avatar"/>
<div className="profile__name">
<span><h4>Shivansh Sharma</h4></span>
<span><p>shivkaansh</p></span>
</div>
<button>Edit profile</button>
<div className="profile_leftFollow">
<div className="profile__options">
<span>< PeopleAltIcon fontSize="small" /></span>
<span>1 follower</span>
</div>
<p>4 following</p>
<div className="profile__options">
<span>< StarBorderIcon fontSize="small"/></span>
<span>3</span>
</div>
</div>
<div className="profile_leftLoc">
<span>< LocationOnIcon fontSize="small" /></span>
<span>India</span>
</div>
</div>
<div className="profile__right">
<div className="profile__rightupper">
<Underlinenav/>
</div>
{template}
</div>
</div>
)
}
export default Profile
I used the prop named template for routing the component in profile.js to toggle between components inside the body. But I think, It is not working as expected,
I want the component of Overview.js on path http://localhost:3000/ and Repo.js on http://localhost:3000/tagname=Repo
Use render attribute and a middleware function to return correct component
<Route
path="/"
render={({location}) => {
const template = checkYourRoute(location) ? Overview : Repo;
return <Profile template={template} />
}
}
>

Passing State of App.js to Child Component

I'm working on the main page of a website and I'd like to have a specific nav/menu bar for the main page and a different one for the other components (the main page hides de "home" button and the others show it).
The issue I have at the moment is that the logic of rendering this menu lives on App and I'm having a hard time to find the proper way to pass the state of my App component to the other components, probably just because of the lack of experience.
import React from "react";
import { BrowserRouter, Route, Link } from "react-router-dom";
import Main from "./main";
import MapContainer from "./mapcontainer";
import Venue from "./venue";
import Schedule from "./schedule";
import Accommodation from "./accommodation";
import Couple from "./couple";
import Honeymoon from "./honeymoon";
import Uploader from "./uploader";
import Friday from "./friday";
import Saturday from "./saturday"
import Sunday from "./sunday";
import Dresscode from "./dresscode";
export class App extends React.Component {
constructor(props) {
super(props);
this.state = {
error: false,
isHome: true
};
}
componentDidMount() {
console.log("App mounted");
}
render() {
function HomeComponentMenu(props) {
return (
<nav className="header-on-app">
<button>Contact Us</button>
<button className="logout-btn">Logout</button>
</nav>
);
}
function AllOtherComponentsMenu(props) {
return (
<nav className="header-on-app">
<button><Link to="/">Home</Link></button>
<button>Contact Us</button>
<button className="logout-btn">Logout</button>
</nav>
);
}
const isHome = this.state.isHome;
let menu;
if (isHome) {
menu = <HomeComponentMenu/>;
} else {
menu = <AllOtherComponentsMenu/>;
}
return (
<BrowserRouter>
<nav className="header-on-app">{menu}</nav>
<div className="app-container">
<Route exact path="/" component={Main} />
<Route exact path="/venue" component={Venue}/>
<Route exact path="/venuemap" component={MapContainer}/>
<Route exact path="/schedule" component={Schedule}/>
<Route exact path="/accommodation" component={Accommodation}/>
<Route exact path="/couple" component={Couple}/>
<Route exact path="/honeymoon" component={Honeymoon}/>
<Route exact path="/uploader" component={Uploader} />
<Route exact path="/friday" component={Friday} />
<Route exact path="/saturday" component={Saturday} />
<Route exact path="/sunday" component={Sunday} />
<Route exact path="/dresscode" component={Dresscode} />
</div>
</BrowserRouter>
);
}
}
Component I'd like to set isHome to false
import MapContainer from "./mapcontainer";
export default class Venue extends React.Component {
constructor(props){
super(props);
this.state = {
error:false,
}
}
render() {
return (
<div className="venue-container">
<h1>Anna & Rodolfo</h1>
<h2><span>_______</span> Venue . Local . Veranstalungsort <span>_______</span></h2>
{this.state.error && <h2 className="error">Ops! Something went wrong.</h2>}
<div className="grid-container-venue">
<div className="item">
<img src="venue.png" alt="Avatar" className="image"/>
<div className="background-grid-items">
<div className="text-address">
<a href="https://www.g71972,15z/data=!4887b!8m2!3d52.47094!4d12.71972">
<p>Kulturschloss</p>
<p>Abcd.30 3456 Berlin </p>
<p>Germany . Alemanha . Deutschland</p>
</a>
</div>
</div>
</div>
<div className="item">
<img src="website.png" alt="Avatar" className="image"/>
<div className="background-grid-items">
<div className="text">
<a href="https://www.kult.de/">
<p>To the Website</p>
<p>Para o Website</p>
<p>Zur Website</p>
</a>
</div>
</div>
</div>
<div className="item">
<img src="transportation.png" alt="Avatar" className="image"/>
<div className="background-grid-items">
<div className="text">
<p>Transportation</p>
<p>Traslado</p>
<p>Transport</p>
</div>
</div>
</div>
<div className="item">
<div className="background-grid-venue">
<div className="map">
<MapContainer/>
</div>
</div>
</div>
</div>
</div>
);
}
}
Since my components are being rendered by React Router, I tried to render props passing it in an inline function and afterwards pass along to the argument I was creating, but somehow it didn't work. Would you have any suggestions on how to solve this? Thank you very much!
To pass a state to a child component, you have to pass it as props of the child component.
e.g.
import React, { Component } from 'react';
import { BrowserRouter as Router, Route } from 'react-router-dom';
import TableView from './TableView'
export default class App extends Component {
state = {
item: 'this is the item'
}
render() {
return(
<Router>
<Route exact path="/home">
<TableView itemList={this.state.item}></TableView>
</Route>
</Router>
)
}
}
to get the props in the child component
import React, { Component } from 'react'
export default class TableView extends Component {
render(){
<React.Fragment>
{this.props.item}
</React.Fragment>
}
}
Hope it helps
EDIT:
It would also help to debug if you have the react devtools addons in your browser to check if the values of the state of each component
To pass props to a react route you have to define it in the render function like this:
<Route exact path="/venue" render={(props) => <Venue updateHomeState={this.updateHomeState}/>}/>
To alter the isHome state on the parent, you could define that function on the parent like:
updateHomeState = (newState) => {
this.setState({ isHome: newState })
}
And then call it in componentDidMount() of your child component like this.props.updateHomeState(newState).

Create-React-App: router is marked as required in Link

I've got a problem with Link in react router in one component. Once I try to use Link, the console shows this error: Failed context type: The context router is marked as required in Link, but its value is undefined. I've seen all similar threads about this problem here, but there's no solution to this exact issue. I'm using all the latest versions of all frameworks and componets (just downloaded everything a couple of days ago), so it's definitely not about upgrading anything.
The structure is like this:
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
import { BrowserRouter as Router, Route} from 'react-router-dom';
import { Link } from 'react-router-dom';
import About from './components/About';
import Posting from './components/Posting';
import Groups from './components/Groups';
ReactDOM.render(<App />, document.getElementById('app'));
ReactDOM.render(
<Router>
<div>
<Route exact path='/' component={About} />
<Route path='/post' component={Posting} />
<Route path='/groups' component={Groups} />
</div>
</Router>,
document.getElementById('content')
);
registerServiceWorker();
App.js
import React, { Component } from 'react';
import { BrowserRouter as Router, Route} from 'react-router-dom';
import { Link } from 'react-router-dom';
import SideMenuUserInfo from './components/sidemenu/SideMenuUserInfo';
import SideMenu from './components/sidemenu/SideMenu';
import SideMenuFooter from "./components/sidemenu/SideMenuFooter";
import TopNav from "./components/topnav/TopNav";
class App extends Component {
render() {
return(
<div className="main_container">
<div className="col-md-3 left_col">
<div className="left_col scroll-view">
<div className="navbar nav_title" style={{border: 0}}>
<i className="fa fa-paw"></i> <span>Logo here</span>
</div>
<div className="clearfix"></div>
<SideMenuUserInfo />
<br />
<SideMenu />
<SideMenuFooter />
</div>
</div>
<TopNav />
<div id="content" className="right_col" role="main">
</div>
<footer>
<div className="pull-right">
Footer text here
</div>
<div className="clearfix"></div>
</footer>
</div>
);
}
}
export default App;
SideMenuUnfoldLink.js
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
class SideMenuUnfoldLink extends Component {
render() {
return(
<li>
<a>
<i className={this.props.faClass}></i>{this.props.text}<span className="fa fa-chevron-down"></span>
</a>
<ul className="nav child_menu">
<li><Link to="/">Home</Link></li> <<<<-- THE PROBLEM IS HERE
</ul>
</li>
);
};
}
export default SideMenuUnfoldLink;
And About.js (as a working example of Link)
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
class About extends Component {
render() {
return (
<div>
<h2>Это About</h2>
<ul>
<li><Link to="/groups">Groups</Link></li>
<li><Link to="/">Main</Link></li>
</ul>
</div>
);
}
}
export default About;
The Link works with the About component like a charm. The error starts to pop up once I use Link in my SideMenuUnfoldLink component.
I suppose the Router is just not initialized by the moment SideMenuUnfoldLink wants to use Link. But how can I go about it?
I've just found the solution. It is to wrap the router around the entire
application to make it available to all components like this:
render() {
return(
<Router>
<div className="main_container">
<div className="col-md-3 left_col">
<div className="left_col scroll-view">
<div className="navbar nav_title" style={{border: 0}}>
<i className="fa fa-paw"></i> <span>Logo here</span>
</div>
<div className="clearfix"></div>
<SideMenuUserInfo />
<br />
<SideMenu />
<SideMenuFooter />
</div>
</div>
<TopNav />
<div id="content" className="right_col" role="main">
</div>
<footer>
<div className="pull-right">
Footer text here
</div>
<div className="clearfix"></div>
</footer>
</div>
</Router>
);
}
And of course removing this part:
ReactDOM.render(
<Router>
<div>
<Route exact path='/' component={About} />
<Route path='/post' component={Posting} />
<Route path='/groups' component={Groups} />
</div>
</Router>,
document.getElementById('content')
);
Here's a more detailed explanation https://reacttraining.com/react-router/
Lots of thanks to the author of that video :)

Categories

Resources