React Router hide App content when click other pages link - javascript

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;

Related

Link tag not working in React Router v6.7

React router v6.7 does add /about to the end of the url but doesn't render the components. Normally putting the url does work though.
Navbar.js:
import React from 'react'
import PropTypes from 'prop-types'
import { Link, BrowserRouter } from 'react-router-dom'
export default function Navbar(props) {
return (
<BrowserRouter>
<nav className={`navbar navbar-expand-lg navbar-${props.mode} bg-${props.mode}`}>
<div className="container-fluid">
<Link className="navbar-brand" to="/">{props.title}</Link>
<button className="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span className="navbar-toggler-icon"></span>
</button>
<div className="collapse navbar-collapse" id="navbarSupportedContent">
<ul className="navbar-nav me-auto mb-2 mb-lg-0">
<li className="nav-item">
<Link className="nav-link active" aria-current="page" to="/">Home</Link>
</li>
<li className="nav-item">
<Link className="nav-link" to="/about">{props.aboutText}</Link>
</li>
<li className="nav-item dropdown">
<Link className="nav-link dropdown-toggle" to="/" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
Dropdown
</Link>
<ul className="dropdown-menu" aria-labelledby="navbarDropdown">
<li><Link className="dropdown-item" to="/">Action</Link></li>
<li><Link className="dropdown-item" to="/">Another action</Link></li>
<li><hr className="dropdown-divider" /></li>
<li><Link className="dropdown-item" to="/">Something else here</Link></li>
</ul>
</li>
<li className="nav-item">
<Link to="/" className="nav-link disabled">Disabled</Link>
</li>
</ul>
<div className="form-check form-switch mx-3">
<input className="form-check-input" type="checkbox" role="switch" id="flexSwitchCheckDefault" onClick={props.toggleDarkMode} />
<label className="form-check-label" htmlFor="flexSwitchCheckDefault">Dark Mode</label>
</div>
<form className="d-flex">
<input className="form-control me-2" type="search" placeholder="Search" aria-label="Search" />
<button className="btn btn-outline-success" type="submit">Search</button>
</form>
</div>
</div>
</nav>
</BrowserRouter>
)
}
Navbar.propTypes = {
title: PropTypes.string.isRequired,
aboutText: PropTypes.string
}
Navbar.defaultProps = {
title: "Enter your Title",
aboutText: "About"
}
App.js
// import logo from './logo.svg';
import { useState } from 'react';
import './App.css';
import About from './components/About';
import Navbar from './components/Navbar';
import TextForm from './components/TextForm';
import {
createBrowserRouter,
RouterProvider,
} from "react-router-dom";
const router = createBrowserRouter([
{
path: "/",
element: <TextForm />,
},
{
path: "/about",
element: <About />
}
]);
function App() {
const [mode, setMode] = useState("light");
const toggleDarkMode = (event) => {
if (event.target.checked) {
setMode("dark");
document.body.style.backgroundColor = "#15181a";
document.body.style.color = "white";
}
else {
setMode("light");
document.body.style.backgroundColor = "white";
document.body.style.color = "black";
}
}
return (
<>
<Navbar title="TextUtils" aboutText="About Us" mode={mode} toggleDarkMode={toggleDarkMode} />
<RouterProvider router={router} />
</>
);
}
export default App;
Expectation:
Link to should render the component into the DOM without reloading.
Reality:
The url gets concatenated but the page actually doesn't render anything.
Your <RouterProvider /> needs to wrap the NavBar component with router prop. Check out the official documentation.
What you're currently doing is wrapping the Navbar but you have provided no router instance. So it doesn't know the routes and which component to render when routes change.
Refactor App.js like this:
<>
<RouterProvider router={router}>
<Navbar title="TextUtils" aboutText="About Us" mode={mode} toggleDarkMode={toggleDarkMode} />
</RouterProvider>
</>
And remove RouterProvider parent component from Navbar
Ok, So the thing is React Router v6.7 docs for getting started does not mention that the elements inside the:
const router = createBrowserRouter(createRoutesFromElements(
<Route path='/' element={<RootLayout />}>
<Route index element={<TextForm />} />
<Route path='/about' element={<About />} />
</Route>
))
Would be rendered wherever the <Outlet /> tag is.
So I made RootLayout page and put it inside that and everything works. Here is what it looks like.
import React from 'react'
import { Outlet } from 'react-router-dom'
import Navbar from '../components/Navbar'
import { useState } from 'react'
export default function RootLayout() {
const [mode, setMode] = useState("light");
const toggleDarkMode = (event) => {
if (event.target.checked) {
setMode("dark");
document.body.style.backgroundColor = "#15181a";
document.body.style.color = "white";
}
else {
setMode("light");
document.body.style.backgroundColor = "white";
document.body.style.color = "black";
}
}
return (
<>
<Navbar title="TextUtils" aboutText="About Us" mode={mode} toggleDarkMode={toggleDarkMode} />
<Outlet />
</>
)
}

object object output of useState hook

Greetings iam in need of help so I am taking an online course of react and I followed sir Kalob step by step but while assigning keyword using usestate() it is printing [object object] instead of the actual keyword which I set using hook and so I tried to look for different solutions from
useState("searching for")
I changed it to
useState({name :"searching for"})
and while assigning it to keyword i changed it from
keyword={searchText}
to
keyword={searchText.name}
but still, it's giving me the same output I am out of solutions any help would be appreciated.
All necessary screenshots are attached.
enter image description here
enter image description here
enter image description here
APP.JS
import Navbar from './components/navbar';
import Home from './components/home';
import React from 'react';
import SearchView from './components/SearchView'
import {useState,useEffect} from 'react';
import AboutView from './components/AboutView';
import {Routes , Route} from 'react-router-dom';
import './App.css';
function App() {
const[searchResults,setSearchResults] = useState([]);
const [searchText,setSearchText] = useState('');
return (
<div>
<Navbar searchText={searchText} setSearchText={setSearchText}/>
<Routes>
<Route path="/" element={<Home />} />
<Route path='/about' element={<AboutView />} />
<Route path='/search' keyword= {searchText}searchResults={searchResults} element ={<SearchView />} />
</Routes>
</div>
);
}
export default App;
Navbar.Js
// import App from "../App"
import React from 'react';
import {Link} from 'react-router-dom';
const Navbar = ({searchText,setSearchText}) => {
const updateSearchText = (e) =>{
setSearchText(e.target.value)
}
return(
<div>
<nav className="navbar navbar-expand-lg bg-light">
<div className="container-fluid">
<button className="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarTogglerDemo03" aria-controls="navbarTogglerDemo03" aria-expanded="false" aria-label="Toggle navigation">
<span className="navbar-toggler-icon"></span>
</button>
<Link className="navbar-brand" to="/">Movie Browser </Link>
<div className="collapse navbar-collapse" id="navbarTogglerDemo03">
<ul className="navbar-nav me-auto mb-2 mb-lg-0">
<li className="nav-item">
<Link className="nav-link active" aria-current="page" to="/">Home</Link>
</li>
<li className="nav-item">
<Link className="nav-link" to="/about">About</Link>
</li>
<li className="nav-item">
<a className="nav-link disabled" href="/">Disabled</a>
</li>
</ul>
<form className="d-flex" role="search">
<input className="form-control me-2" type="search" placeholder="Search" aria-label="Search" value={searchText}
onChange={updateSearchText}/>
<button className="btn btn-outline-success" type="submit">Search</button>
</form>
</div>
</div>
</nav>
</div>
)
}
export default Navbar;
SearchView.js
import React from "react";
import Hero from "./Hero";
const SearchView =(keyword,searchResults)=>{
const title = `You are searching for ${keyword}`
console.log(searchResults,"are the search results")
return(
<div>
<Hero text ={title} />
</div>
)
}
export default SearchView;
Pass the props that SearchView should have through the element prop while calling the component.
<Route
path='/search'
element={
<SearchView keyword={searchText} searchResults={searchResults} />
}
/>
And your output is [object Object] because you're logging the props object, not the keyword string. Add the destructuring assignment of the props to actually get the props that are being passed.
const SearchView = ({ keyword, searchResults }) => {
const title = `You are searching for ${keyword}`;
return (
<div>
<Hero text ={title} />
</div>
);
}

React Router DOM is not redirecting to new page without refrest

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

Link routes in react changes the link but nothing is changing in the content of the page

I'm trying to make a navbar using react , but although the link has changed , the content never being changed !
routes in my App.js :
import { BrowserRouter as Router , Routes, Route } from "react-router-dom";
import Layout from './hocs/Layout';
import Home from './components/Home';
import Blog from './components/Blog';
import BlogDetail from './components/BlogDetail';
import Category from './components/Category';
const App = () => (
<Router>
<Layout>
<Routes>
<Route exact path = '/' component = {Home} />
<Route exact path = '/blog' component = {Blog} />
<Route exact path = '/category/:id' component = {Category} />
<Route exact path = '/blog/:id' component = {BlogDetail} />
</Routes>
</Layout>
</Router>
);
export default App ;
Home.js file , the content "Home" doesn't appear , although the link changed:
import React from "react";
const Home = () => (
<>
<div>
Home
</div>
</>
);
export default Home;
Also the content of Blog.js file doesn't appear "same as Homel.js":
import React from "react";
const Blog = () => (
<div>
blog
</div>
);
code of navbar Navbar.js using bootstrap :
import React from "react";
import {Link, NavLink} from 'react-router-dom';
const Navbar = () => (
<div>
<nav className="navbar navbar-expand-lg navbar-light bg-light">
<div className="container-fluid">
<Link className="navbar-brand" to="/">Around the world </Link>
<button className="navbar-toggler"
type="button"
data-bs-toggle="collapse"
data-bs-target="#navbarNav"
aria-controls="navbarNav"
aria-expanded="false"
aria-label="Toggle navigation">
<span className="navbar-toggler-icon"></span>
</button>
<div className="collapse navbar-collapse" id="navbarNav">
<ul className="navbar-nav">
<li className="nav-item">
<NavLink className="nav-link active" aria-current="page" exact to = '/'>home</NavLink>
</li>
<li className="nav-item">
<NavLink className="nav-link" exact to = '/blog'>Blog</NavLink>
</li>
</ul>
</div>
</div>
</nav>
</div>
);
export default Navbar;
Layout.js:
import React from "react";
import Navbar from '../components/Navbar';
const Layout = (props) => (
<div>
<Navbar />
{props.children}
</div>
);
export default Layout;
Nothing is rendered because you are not correctly using the Route component's element prop to render the routed components. In react-router-dom#6 gone are the component and render and children render function props, replaced by a single element prop taking a ReactElement, a.k.a. JSX.
Route
declare function Route(
props: RouteProps
): React.ReactElement | null;
interface RouteProps {
caseSensitive?: boolean;
children?: React.ReactNode;
element?: React.ReactElement | null; // <-- routed component
index?: boolean;
path?: string;
}
const App = () => (
<Router>
<Layout>
<Routes>
<Route path='/' element={<Home />} />
<Route path='/blog' element={<Blog />} />
<Route path='/category/:id' element={<Category />} />
<Route path='/blog/:id' element={<BlogDetail />} />
</Routes>
</Layout>
</Router>
);

React component does'nt re-render with react router on url change

strong textI have a carousel component that I created in a jsx file. When I go to a different page and navigate back to that page the carousel doesn't re-render. I have tried updating my routes as well as looking into all possible css causes. I see that the carousel container is there but none of the content is showing.
Below is my jsx file:
import React, { Component, Fragment } from 'react';
import { Link } from 'react-router-dom'
import { Button, Icon } from 'react-materialize'
import ReactDOM from 'react-dom'
import './Carousel.css';
class Carousel extends Component {
render() {
return (
<Fragment>
<div>
<div class="row">
<div class="col s12">
{/* <!--Images and carousel items below --> */}
<div width="100%" id="carousel-div" class="carousel userInput">
<div class="left">
<a href="Previo" class="movePrevCarousel middle-indicator-text waves-effect waves-light">
<i class="material-icons left middle-indicator-text">chevron_left</i>
</a>
</div>
<a class="carousel-item submitBTN" id="letters" data-search='Sports' href="#letters">
<img height="190" width="400" src="https://toddlermasterclass.com/wp-content/uploads/2015/07/Fun-Games-For-Preschoolers.png"
alt="" />
</a>
<a class="carousel-item submitBTN" id="numbers" data-search='Music' href="#numbers">
<img height="190" width="400" src="http://imgsdown.1mobile.com/group1/M00/A5/58/S36rZlagE-mAOxmfAAQhEBsG6mg860.png" alt="" />
</a>
<a class="carousel-item submitBTN" id="colors" data-search='Technology' href="#colors">
<img height="190" width="400" src="https://i.ytimg.com/vi/e1dHmEJcMG0/maxresdefault.jpg" alt="" />
</a>
<a class="carousel-item submitBTN" id="memory-match" data-search='Food' href="#memory-match">
<img height="190" width="400" src="https://images-na.ssl-images-amazon.com/images/I/713UI4Vy1-L.png" alt="" />
</a>
<a class="carousel-item submitBTN" id="shapes" data-search='Arts' href="#shapes!">
<img height="190" width="400" src="https://i.ytimg.com/vi/AQbnbrTHgtA/maxresdefault.jpg" alt="" />
</a>
<a class="submitBTN btn waves-effect waves-light" type="submit" name="action">Submit
<i class="material-icons right">send</i>
</a>
<div class="right">
<a href="Siguiente" class="moveNextCarousel middle-indicator-text waves-effect waves-light">
<i class="material-icons right middle-indicator-text">chevron_right</i>
</a>
</div>
</div>
</div>
</div>
</div>
);
</Fragment>
)
}
}
export default Carousel;
Below is my router file:
import React from 'react';
import { BrowserRouter as Router, Route } from 'react-router-dom';
import Navbar from './components/Navbar';
import Parents from './components/Parents';
import Login from './components/Login';
import Home from './components/Home';
import About from './components/About'
import Cards from './components/cardGame';
import Carousel from './components/Carousel';
/* import ReactCarousel from './components/ReactCarousel'; */
import ColorGame from './components/colorGame/colorGame';
import NumberGame from './components/NumberGame/numberGame';
const AppRouter = () => {
// class AppRouter extends Component {
// render() {
return (
<Router>
<div>
{/* edit username */}
<Navbar username='User' message='welcome back!'/>
<Route path='/Login' component={Login} />
<Route path='/Home' component={Home} />
<Route path='/About' component={About} />
<Route path='/Parents' component={Parents} />
<Route path='/colorGame' component={ColorGame} />
<Route path='/cardGame' component={Cards} />
<Route path='/numberGame' component={NumberGame} />
</div>
</Router>
)
}
// }
export default AppRouter;
Below is the Home.js file that I'm rendering my carousel in:
import React, { Component, Fragment } from 'react';
import { Link } from 'react-router-dom';
import { Button, Icon } from 'react-materialize'
import './Home.css';
import ReactDOM from 'react-dom';
import Carousel from '../Carousel';
/* import ReactCarousel from '../ReactCarousel'; */
class Home extends Component {
render() {
return (
<Fragment>
<Carousel />
{/* <ReactCarousel /> */}
</Fragment>
)
}
}
export default Home;
Here is the Navbar component
import React, { Fragment } from 'react';
import { Link } from 'react-router-dom'
import './Navbar.css'
const Navbar = props => {
return (
<Fragment>
<nav className="navigation_container">
<div className="l-triangle-top"></div>
<div className="l-triangle-bottom"></div>
<div className="rectangle">
<div className="navigation">
<Link className='nav-item nav-link' to='/Parents'>Parents Place</Link>
<ul className="right hide-on-med-and-down">
<li><Link className='nav-item nav-link' to='/Home'>Home</Link></li>
<li><Link className='nav-item nav-link' to='/Login'>Logout</Link></li>
<li><Link className='nav-item nav-link' to='/About'>About</Link></li>
</ul>
</div>
</div>
<div className="r-triangle-top"></div>
<div className="r-triangle-bottom"></div>
</nav>
</Fragment>
)
}
export default Navbar;
Would someone help me see why the carousel is not rendering when I navigate back to my home page?
Can you show your <Navbar /> component? Since your home path is path='/Home' make sure you have <Link to='/**H**ome'/> in your NavBar

Categories

Resources