I just started to learn react js and created a sample app, in which application has header, footer with content. To add header footer on each page I created root.js and include header, footer there.
as props.children can render each nested route I added {this.props.children} inside root.js.
But When I clicked on any Links, nothing is happening, previous page(home) still rendered.
I could not understand whats going on and how to resolve this. Please help me, It already took me 2 days searching on google.
Edit:
Now working fine. Problem was that I added links inside
But now another problem is happening.
whenever I refresh page everything has gone. pages are not found shows
Edit:
Now working after page refresh by adding these line in
package.json
"scripts": {
"start": "npm run build",
"build": "webpack -d && cp src/index.html dist/index.html && webpack-dev-server --content-base src/ --inline --hot --history-api-fallback",
"build:prod": "webpack -p && cp src/index.html dist/index.html"
}
index.js
import React from "react";
import { render } from "react-dom";
import { Home } from "./pages/home/index.jsx";
import { Root } from "./component/layout/root";
import { Blog } from "./pages/blog/index.jsx";
import { About } from "./pages/about/index.jsx";
import { Contact } from "./pages/contact/index.jsx";
import { Portfolio } from "./pages/portfolio/index.jsx";
import { Services } from "./pages/services/index.jsx";
import { Match } from 'react-router';
import {BrowserRouter as Router, Route} from 'react-router-dom'
import {IndexRoute, browserHistory, Switch } from 'react-router';
class App extends React.Component {
render(){
return(
<Router>
<Root>
<Switch>
<Route exact path={"/"} component={Home} />
<Route path="/blog" component={Blog}/>
<Route path="/contact" component={Contact}/>
<Route path="/portfolio" component={Portfolio}/>
<Route path="/about" component={About}/>
<Route path="/services" component={Services}/>
<Route path="/home" component={Home} />
</Switch>
</Root>
</Router>
);
}
}
render( <App /> , window.document.getElementById("app"));
root.js
import React from 'react';
import { render } from 'react-dom';
import { Header } from './header/index';
import { Footer } from './footer/index';
export class Root extends React.Component {
constructor(props){
super();
}
render(){
return(
<div>
<Header/>
{this.props.children}
<Footer/>
</div>
);
}
}
Components:
/blog/index.jsx
/home/index.jsx
/contact/index.jsx
import React from "react";
import {render} from "react-dom";
export class Contact extends React.Component {
render() {
return (
< div id = "fh5co-contact-section" >
<div className="container">
<div className="row">
<div className="col-md-6 col-md-offset-3 text-center fh5co-heading">
<h2>Contact</h2>
<p>
<span>Created with
<i className="sl-icon-heart"></i>
by the fine folks at
FreeHTML5.co
</span>
</p>
</div>
</div>
<div className="row">
<div className="col-md-3">
<h3>Contact Info.</h3>
<ul className="contact-info">
<li>
<i className="sl-icon-map"></i>198 West 21th Street, Suite 721 New York NY 10016</li>
<li>
<i className="sl-icon-phone"></i>+ 1235 2355 98</li>
<li>
<i className="sl-icon-envelope-open"></i>
info#yoursite.com
</li>
<li>
<i className="sl-icon-globe-alt"></i>
www.yoursite.com
</li>
</ul>
</div>
<div className="col-md-8 col-md-push-1 col-sm-12 col-sm-push-0 col-xs-12 col-xs-push-0">
<div className="row">
<div className="col-md-6">
<div className="form-group">
<input className="form-control" placeholder="Name" type="text" /></div>
</div>
<div className="col-md-6">
<div className="form-group">
<input className="form-control" placeholder="Email" type="text" /></div>
</div>
<div className="col-md-12">
<div className="form-group">
<textarea
name=""
className="form-control"
id=""
cols="30"
rows="7"
placeholder="Message"></textarea>
</div>
</div>
<div className="col-md-12">
<div className="form-group">
<input value="Send Message" className="btn btn-primary" type="submit"/></div>
</div>
</div>
</div>
</div>
</div>
</div>
);
}
}
header.js
import React from "react";
import {render} from "react-dom";
import { Link } from "react-router-dom";
import { BrowserRouter as Router } from "react-router-dom";
export const Header = (props) => {
return(
<header id="fh5co-header" role="banner">
<div className="container">
<div className="header-inner">
<h1><i className="sl-icon-energy"></i><Link to="/">Lesser</Link></h1>
<nav role="navigation">
<ul>
<li><Link className="active" to="/">Home</Link></li>
<li><Link to="/blog">Blog</Link></li>
<li><Link to="/portfolio">Portfolio</Link></li>
<li><Link to="/services">Services</Link></li>
<li><Link to="/about">About</Link></li>
<li><Link to="/contact">Contact</Link></li>
</ul>
</nav>
</div>
</div>
</header>
);
};
I don't see any links in your post but in any case you have to use the NavLink component from React-Router-Dom and replace any anchor tags with it.
Example:
<NavLink to="/blog">Blog</NavLink>
instead of:
Blog
also for sake of readability and clean code it is better to seperate sections into components, form in its own component, contact info in its own and so on
You can import Link from react-router-dom:
import Link from 'react-router-dom/Link';
and then use this <Link to='url'>display text</Link>
Related
I want routing facility in my App so I have use react-router-dom for it. I have a checkout button which on clicking should redirect to <Checkout/> page but only the url is changing & not directing to the checkout page until unless user refreshes manually.
Here's my code:
App.js
import "./App.css";
import Header from "./Header";
import Home from "./Home";
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";
import Checkout from "./Checkout";
function App() {
return (
<Router>
<div className="App">
<Switch>
<Route exact path="/checkout">
<Header />
<Checkout />
</Route>
<Route path="/">
<Header />
<Home />
</Route>
</Switch>
</div>
</Router>
// header
// home
);
}
export default App;
Checkout Button (Header.js):
import React from "react";
import "./Header.css";
import { GrSearch } from "react-icons/gr";
import { MdShoppingBasket } from "react-icons/md";
import { Link, useHistory} from "react-router-dom";
import { useStateValue } from "./StateProvider";
const Header = () => {
const [{ basket }, dispatch] = useStateValue();
const history = useHistory();
return (
<div className="header">
<Link to="/">
<img
className="header__logo"
src="http://pngimg.com/uploads/amazon/amazon_PNG11.png"
alt=""
></img>
</Link>
<div className="header__search">
<input className="header__searchInput" type="text"></input>
<GrSearch className="header__searchIcon" />
</div>
<div className="header__nav">
<div className="header__option">
<span className="header__optionLineOne">Hello Guest </span>
<span className="header__optionLineTwo">Sign In</span>
</div>
<div className="header__option">
<span className="header__optionLineOne">Returns </span>
<span className="header__optionLineTwo">& Orders</span>
</div>
<div className="header__option">
<span className="header__optionLineOne">Your </span>
<span className="header__optionLineTwo">Prime</span>
</div>
<Link to="/checkout">
<div className="header__optionBasket">
<MdShoppingBasket onClick={ ()=> history.push("/checkout")}/>
<span className="header__optionLineTwo header__basketCount">
{basket?.length}
</span>
</div>
</Link>
</div>
</div>
);
};
export default Header;
May anyone tell me why it's not redirecting to checkout page. I am using React-router-dom v5.2.0
Thanks
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} />
}
}
>
I want to hide app component content when I click on other component pages link.
Right now, when I click other links like about us, then it shows both app component and about us page component. But I want show only about us content once I click on about us page.
Also, when I define App component patch as a "/" then application keeps loading.
Below are the code
App.js
import React, { Component } from "react";
import Navigation from "./components/Navigation";
import data from "./data";
class App extends Component {
constructor(props) {
super(props);
this.state = {
data: [],
// data: false
};
}
render() {
return (
<div className="container">
<Navigation />
{data.map((link) => (
<div className="card mb-3" key={link.Title}>
<div className="row no-gutters">
<div className="col-md-5">
<img
src={require("./images/" + link.Img)}
className="card-img"
alt=""
/>
</div>
<div className="col-md-7">
<div className="card-body">
<h5 className="card-title">{link.Title}</h5>
<p className="card-text">{link.Desc.halfDesc}</p>
<p className="card-text">
<small className="text-muted">{link.date}</small>
</p>
<button type="button" className="btn btn-dark float-right">
Read More
</button>
</div>
</div>
</div>
<FullDescription />
</div>
))}
</div>
);
}
}
const FullDescription = (props) => (
<div className="modalbox">
<p>fsdf</p>
</div>
);
export default App;
Navigation.Js Everything is working fine only App home page content show which i don't want when i click other pages
import React, { Component } from "react";
import { BrowserRouter as Router, Route, Link, Switch } from "react-router-dom";
import Api from "./Api";
import News from "./News";
import Website from "./Website";
class Navigation extends Component {
render() {
return (
<Router>
<ul className="nav justify-content-center mb-4 navigation">
<li className="nav-item">
<Link className="nav-link" to="/Api">
Api
</Link>
</li>
<li className="nav-item">
<Link className="nav-link" to="/News">
News
</Link>
</li>
<li className="nav-item">
<Link className="nav-link" to="/Website">
Website
</Link>
</li>
</ul>
<Switch>
<Route exact path="/Api" component={Api}></Route>
<Route exact path="/News" component={News}></Route>
<Route exact path="/Website" component={Website}></Route>
</Switch>
</Router>
);
}
}
export default Navigation;
For this to work you need to put content of app.js inside another component because right now it doesnt have a route to hide itself when going to other page. So you need to treat the component just like your rest components (Api.js, News.js) etc..
NewAppComponent.js
import React, { Component } from "react";
import { Link } from "react-router-dom";
class Navigation extends Component {
render() {
return (
<ul className="nav justify-content-center mb-4 navigation">
<li className="nav-item">
<Link className="nav-link" to="/Api">
Api
</Link>
</li>
<li className="nav-item">
<Link className="nav-link" to="/News">
News
</Link>
</li>
<li className="nav-item">
<Link className="nav-link" to="/Website">
Website
</Link>
</li>
</ul>
);
}
}
export default Navigation;
App.js
import React, { Component } from "react";
import Navigation from "./components/Navigation";
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import NewAppComponent from "./NewAppComponent";
import Api from "./Api";
import News from "./News";
import Website from "./Website";
class App extends Component {
render() {
return (
<div className="container">
<Router>
<Navigation />
<Switch>
<Route exact path="/" component={NewAppComponent}></Route>
<Route path="/Api" component={Api}></Route>
<Route path="/News" component={News}></Route>
<Route path="/Website" component={Website}></Route>
</Switch>
</Router>
</div>
);
}
}
export default App;
NewAppComponent.js
// NewAppComponent.js
import React, { Component } from "react";
import data from "./data";
class NewAppComponent extends Component {
constructor(props) {
super(props);
this.state = {
data: [],
// data: false
};
}
render() {
return (
<div className="container">
{data.map((link) => (
<div className="card mb-3" key={link.Title}>
<div className="row no-gutters">
<div className="col-md-5">
<img src={require("./images/" + link.Img)} className="card-img" alt="" />
</div>
<div className="col-md-7">
<div className="card-body">
<h5 className="card-title">{link.Title}</h5>
<p className="card-text">{link.Desc.halfDesc}</p>
<p className="card-text">
<small className="text-muted">{link.date}</small>
</p>
<button type="button" className="btn btn-dark float-right">
Read More
</button>
</div>
</div>
</div>
<FullDescription />
</div>
))}
</div>
);
}
}
const FullDescription = (props) => (
<div className="modalbox">
<p>fsdf</p>
</div>
);
export default NewAppComponent;
i have component that import a Link from react-router-dom
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
class Sidebar extends Component{
render() {
return (
<div className="be-left-sidebar">
<div className="left-sidebar-wrapper">Blank Page
<div className="left-sidebar-spacer">
<div className="left-sidebar-scroll">
<div className="left-sidebar-content">
<ul className="sidebar-elements">
<li className="divider">Menu</li>
<li className="parent"><i className="icon mdi mdi-home" /><span>Home</span>
<ul className="sub-menu">
<li><Link to='/'>Home</Link>
</li>
</ul>
</li>
</ul>
</div>
</div>
</div>
<div className="progress-widget">
<div className="progress-data"><span className="progress-value">60%</span><span className="name">Current Project</span></div>
<div className="progress">
<div style={{width: '60%'}} className="progress-bar progress-bar-primary" />
</div>
</div>
</div>
</div>
);
}
};
export default Sidebar;
then console.log shows an error
Warning: Failed context type: The context router is marked as required in Link, but its value is undefined.
Cannot read property 'history' of undefined
`
i am new in react and i am using react router v4.1.1
anyone can help me?
thanks
Make sure you have your component appearing inside <Router> component.
In React router v4, we have Switch, Route and Link components that we import from react-router-dom and configure our router as follows:
import { Switch, Route, Link } from 'react-router-dom';
<span>LINKS:</span>
<ul>
<li onClick={this.props.goToDefault}><Link to={'/'}>Go To Default</Link></li>
<li onClick={this.props.goToSub1}><Link to={'/left-sub1'}>Go To One</Link></li>
<li onClick={this.props.goToSub2}><Link to={'/left-sub2'}>Go To Two</Link></li>
</ul>
<Switch>
<Route exact path='/' component={LeftSubDefault} />
<Route path='/left-sub1' component={LeftSubOne} />
<Route path='/left-sub2' component={LeftSubTwo} />
</Switch>
In the app.js or whatever your entry file is. Wrap your App component inside BrowserRouter as follows:
import { BrowserRouter } from 'react-router-dom';
<BrowserRouter>
<App />
</BrowserRouter>
Here is a wonderful article that may help.
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 :)