React Page Refresh the Whole Page after Clicking on a link - reactjs

I've just started using reactJS and i am integrating an HTML admin template in react which has header, sidebar, footer and the main section content.
One thing i'm a bit curious is whenever i click links in the main section content, only the specific section dynamically loads, but when i click on links in sidebar the entire page reloads, why is it so? Below is the code that i'm following
App.js
import React from 'react';
import { BrowserRouter } from 'react-router-dom';
import Header from './Components/Header';
import Content from './Components/Content';
import Footer from './Components/Footer';
import Sidebar from './Components/Sidebar';
const App = () => {
return(
<BrowserRouter>
<Header/>
<Sidebar/>
<Content/>
<Footer/>
</BrowserRouter>
);
}
export default App;
Header.jsx
import React from 'react';
import logo from '../stack.png';
const Header = () => {
return(
<nav>
</nav>
);
}
export default Header;
Sidebar.jsx
import React from 'react';
import { Link } from 'react-router-dom';
const Sidebar = () => {
return(
<aside>
<div className="main-menu menu-fixed menu-dark menu-accordion menu-shadow" data-scroll-to-active="true">
<div className="main-menu-content">
<ul className="navigation navigation-main" id="main-menu-navigation" data-menu="menu-navigation">
<li style={{'margin': '25px 0 0 0'}} className="active nav-item">
<Link to="/dashboard">
<i className="ft-home"></i>
<span className="menu-title">
Dashboard
</span>
</Link>
</li>
<li className="nav-item"></i><span className="menu-title" data-i18n="">Create</span>
<ul className="menu-content">
<li className=" menu-item">
<Link to="/create">
<span className="menu-title">
Create New
</span>
</Link>
</li>
<li className=" menu-item">
<Link to="/createxyz">
<span className="menu-title">
Create XYZ
</span>
</Link>
</li>
</ul>
</li>
</ul>
</div>
</div>
</aside>
);
}
export default Sidebar;
Content.jsx
import React from 'react';
import { Switch, Route } from 'react-router-dom';
import Dashboard from './Dashboard';
import Enter from './Enter';
import Enterxyz from './Enterxyz';
const Content = () => {
return(
<Switch>
<Route exact path="/" component={Dashboard} />
<Route path="/dashboard" component={Dashboard} />
<Route path="/create" component={Enter} />
<Route path="/createxyz" component={Enterxyz} />
</Switch>
);
}
export default Content;
Footer.jsx
import React from 'react';
function Footer()
{
return(
<footer className="footer footer-static footer-light navbar-border">
<p className="clearfix blue-grey lighten-2 text-sm-center mb-0 px-2">
<span className="float-md-left d-block d-md-inline-block">© 2020
<a className="text-bold-800 grey darken-2" href="">
xyz
</a> (All Rights Reserved)
</span>
</p>
</footer>
);
}
export default Footer;
Code snippet in import Enter from './Enter';
import React from 'react';
import { Link } from 'react-router-dom';
const Enter = () => {
return(
<div className="app-content content">
<div className="content-wrapper">
<div className="content-body">
<div className="row">
<div className="col-md-12">
<div className="card" style={{'height': 'auto'}}>
<div className="card-header">
<h4 className="card-title" id="basic-layout-form">Create New Client</h4>
<a className="heading-elements-toggle"><i className="fa fa-ellipsis-v font-medium-3"></i></a>
<div className="heading-elements">
<ul className="list-inline mb-0">
<li><Link to="/dashboard">Dashboard</Link></li>
<li><i className="ft-chevrons-right"></i></li>
<li><a>Create</a></li>
<li><i className="ft-chevrons-right"></i></li>
<li><Link to="/create">Enter New</Link></li>
</ul>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
);
}
export default Enter;
in the Enter code snippet there are 2 links(Breadcrumbs) when i click on them the page loads dynamically without refresh.
But when i click on the links in sidebar, the entire page reloads to display the content, why is it so? What is wrong?

Related

React JS Navigation Bar

App.js
import NewsSec from "./News/NewsSec";
import ScoreSec from "./ScoreSec/ScoreSec";
import Menu from "./Sidebar/Menu";
import "./styles.css";
import { GiHamburgerMenu } from "react-icons/gi";
import React, { useState } from "react";
export default function App() {
const [showMediaIcons, setShowMediaIcons] = useState(false);
return (
<div className="App">
<div className="head">
<div className="navicon">
<a
href="/"
onClick={() => {
setShowMediaIcons(!showMediaIcons);
}}
>
<GiHamburgerMenu />{" "}
</a>
</div>
<div className="logo">Project</div>
<div className="weather">weather section</div>
</div>
<div className="main">
<div className="nav-section">
<Menu classes={showMediaIcons ? "mobile-view navbar" : "navbar"} />
</div>
<div className="news-section">
<NewsSec />
</div>
<div className="score-section">
<ScoreSec />
</div>
</div>
</div>
);
Menu.js
import React from "react";
import "./Navbar.css";
const Menu = (props) => {
return (
<>
<div className={props.classes}>
<ul>
<li>Home</li>
<li>News</li>
<li>Sports</li>
<li>Weather</li>
<li>About</li>
</ul>
</div>
</>
);
};
export default Menu;
i was trying to make a responsive navigation bar. the navigation bar is actually a sidebar. i used the props to pass the 'className' from App.js to Menu.js because i called the function in App.js
For testing, I tried changing the nav colour to Red. But on clicking Hamburger icon, the colour changes to Red and changed back to normal automatically. Please help folks
It seems that a might be reloading the page with href="/", resetting the state showMediaIcons to its initial value of false.
If the purpose of GiHamburgerMenu is to toggle display for Menu, it might not need to be wrapped in a, instead try add the onClick on the icon or on the wrapping div:
<div className="navicon">
<GiHamburgerMenu
onClick={() => {
setShowMediaIcons((prev) => !prev);
}}
/>
</div>

White Blank Screen after using import { Link } from "react-router-dom";

This is exactly the code I copied in the video tutorial but I don't know why I got a blank white screen on my browser while the other (original) code doesn't get a blank screen after importing the { Link } from "react-router-dom"; How do you fix this? I can't find any solutions.
Here is my App.js
import React from "react";
import Navbar from "./components/Nav/Navbar";
function App () {
return (
<div>
<Navbar/>
</div>
);
}
export default App;
This is my Navbar.jsx
import React from "react";
import { Link } from "react-router-dom";
import Logo from "../../assets/Logo.png";
const Navbar = () => {
return (
<nav className="bg-white">
<div className="flex items-center font-medium justify-around">
<div>
<img src={Logo} alt="logo" className="md:cursor-pointer" />
</div>
<ul>
<li>
<Link to="/" className="py-7 px-3 inline-block">
Home
</Link>
</li>
</ul>
</div>
</nav>
);
};
export default Navbar;

i want to build sidebar on my own but the function don't work

Sorry for my bad English speak please help me to build a responsive sidebar menu. when i try to build a sidebar menu responsive I reach this type of error : TypeError: document.getElementByClassName is not a function. I haven't an idea where's the error exactly so this is my code of the sidebar menu:
import React from 'react';
import {useEffect} from 'react';
import SideNav, { Toggle, Nav, NavItem, NavIcon, NavText } from '#trendmicro/react-sidenav';
import '#trendmicro/react-sidenav/dist/react-sidenav.css';
import {listProducts} from '../actions/productActions';
import {useSelector, useDispatch} from 'react-redux';
function w3_open() {
document.getElementByClassName("sidebar").style.width = "100%";
document.getElementByClassName("sidebar").style.display = "block";
}
function w3_close() {
document.getElementByClassName("sidebar").style.display = "none";
}
export default function SideBarMenu() {
const dispatch = useDispatch();
useEffect(()=> {
dispatch(listProducts);
}, [])
const productList = useSelector((state) => state.productList);
const {products} = productList;
console.log(products);
return (
<div className="wrapper" >
<div className="section">
<div className="top_navbar">
<div className="hamburger">
<a href="#">
<i className="fa fa-bars" onClick={w3_open(), w3_close()} ><span className="bar-icon"> All products </span></i>
</a>
</div>
</div>
</div>
<div className="sidebar">
profile image & text
menu item
</div>
</div>
)
}
and this is the app.js file :
import React from 'react';
import {BrowserRouter, Routes, Route} from 'react-router-dom';
import HomePage from './Pages/HomePage';
import ProductPage from './Pages/productPage';
import SideBarMenu from './components/SideBarMenu';
function App() {
return (
<BrowserRouter>
<div className="grid-container" >
<header className="row" >
<div>
<a className="brand" href="/">My shop</a>
</div>
<div>
Cart
Sign In
</div>
</header>
<main>
<SideBarMenu ></SideBarMenu>
<Routes>
<Route path='/product/:id' element={<ProductPage /> } />
<Route path='/' element={<HomePage />} exact />
</Routes>
</main>
<footer className="row center" >All right reserved</footer>
</div>
</BrowserRouter>
);
}
export default App;
document.getElementByClassName(...) doesn't exist in JavaScript. You should use document.getElementsByClassName(...) (notice the plural in Elements).
Replace document.getElementByClassName("sidebar") with document.getElementsByClassName("sidebar")[0].
Update
To fix the error that you have right now, I would suggest to use a variable and useState Hook to display or hide the sidebar.
Example:
const [open, setOpen] = useState(false)
const handleSidebar = () => {
setOpen(!open)
}
return(
<div className = "wrapper" >
<div className = "section">
<div className = "top_navbar">
<div className = "hamburger">
<a href = "#">
<i className="fa fa-bars" onClick = {handleSidebar}><span className = "bar-icon"> All products </span></i>
</a>
</div>
</div>
</div>
{ open
? <div className = "sidebar">
profile image & text menu item
</div>
: null
}
</div>
)

How to get another component when I click h1 tag in react using hooks?

I am working on react project in that project Home.js is Parent component and Test.js is Child component. In Home.js component I have tag here what I am trying to do is If I Click tag I need to call Test.js component. For this In Home.js I created one function and, To that function I passed Test.js component. and I passed that function via onClick method to h1 tag but its not working. How to achieve this.
This is App.js
import React from 'react';
import './App.css';
import {
BrowserRouter as Router,
Switch,
Route,
Link
} from "react-router-dom";
import Navbar from './Components/Navbar/Navbar';
import Home from "./Pages/Home/Home";
import Test from "./Pages/Test/Test";
function App() {
return (
<div className="App">
<Router>
<Navbar></Navbar>
<Switch>
<Route exact path='/'><Home></Home></Route>
<Route path='/test'><Test></Test></Route>
</Switch>
</Router>
</div>
);
}
export default App;
This is Navbar.js
import React from 'react';
import './Navbar.css';
import { Link } from 'react-router-dom';
export default function Navbar() {
return (
<div className='container'>
<div className='row'>
<div className='col-12'>
<nav className="navbar navbar-expand-lg navbar-light bg-light">
<a className="navbar-brand" href="#">Navbar</a>
<button className="navbar-toggler" type="button" data-toggle="collapse" data-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 active">
<Link className='nav-link' to='/'>Home</Link>
</li>
</ul>
</div>
</nav>
</div>
</div>
</div>
)
}
This is Home.js
import React from 'react';
import './Home.css';
import { Link } from 'react-router-dom';
import Test from '../Test/Test';
export default function Home() {
const Test = () => {
<Test></Test>
}
return (
<div className='container'>
<div className='row'>
<div className='col-12'>
<div>
<h1 onClick={Test}>Cruse</h1>
</div>
</div>
</div>
</div>
)
}
This is Test.js
import React from 'react'
export default function Test() {
return (
<div>
<h1>Test works</h1>
</div>
)
}
I would say you are using event handlers wrong. Their purpose is to produce some kind of side effects, and they don't return a direct result. If you wish to show new element on click i recommend using react state and something like this:
export default function Home() {
const [isTestVisible, setTestVisible] = useState(false);
const showTest= () => setTestVisible(true);
return (
<div className='container'>
<div className='row'>
<div className='col-12'>
<div>
<h1 onClick={showTest}>Cruse</h1>
{isTestVisible && <Test />}
</div>
</div>
</div>
</div>
)
}
In your state you could save different props for each test component so you can customize them. Hope this helps :)
Using states is the correct answer as #Kaca992 said. But for what you do, you can do something like this:
const Test = () => {
ReactDOM.render(<Test/>, document.getElementsByTagName("h1")[0]);
}

Calling function in App.js from another component

I'm new to ReactJS and want to use this library: https://github.com/teodosii/react-notifications-component
It states that "You must place ReactNotificationsComponent component at the root level of the application in order to work properly, otherwise it might conflict with other DOM elements due to the positioning."
I followed the usage guide, but I'm not sure how to call the addNotification function from a child component.
App.js
import React, { Component } from 'react'
import ReactNotification from "react-notifications-component"
import Header from './components/Header'
class App extends Component {
constructor() {
super()
this.addNotification = this.addNotification.bind(this)
this.notificationDOMRef = React.createRef()
}
addNotification() {
this.notificationDOMRef.current.addNotification({
title: "Awesomeness",
message: "Awesome Notifications!",
type: "success",
insert: "top",
container: "top-right",
animationIn: ["animated", "fadeIn"],
animationOut: ["animated", "fadeOut"],
dismiss: { duration: 5000 },
dismissable: { click: true }
})
}
render() {
return (
<div>
<ReactNotification ref={this.notificationDOMRef} />
<Header />
</div>
)
}
}
export default App
Header.js
import React, { Component } from 'react'
import logo from "../assets/images/logo/logo-light.png"
import { BrowserRouter as Router, Route, NavLink, Switch } from "react-router-dom"
import Home from '../pages/Home'
import Apply from '../pages/Apply'
export default class Header extends Component {
render() {
return (
<Router>
<div>
<Route render={({ location }) => (
<header id="navbar-spy" className="header header-1 header-dark header-fixed">
<nav id="primary-menu" className="navbar navbar-fixed-top">
<div className="container">
<div className="navbar-header">
<button type="button" className="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar-collapse-1" aria-expanded="false">
<span className="sr-only">Toggle navigation</span>
<span className="icon-bar"></span>
<span className="icon-bar"></span>
<span className="icon-bar"></span>
</button>
<img className="logo-light" src={logo} alt="Logo" draggable="false" />
</div>
<div className="collapse navbar-collapse pull-right" id="navbar-collapse-1">
<ul className="nav navbar-nav nav-pos-right navbar-left">
<li className="">
<NavLink to="/" className="menu-item">Home</NavLink>
</li>
<li className="">
<NavLink to="/apply" className="menu-item">Apply</NavLink>
</li>
</ul>
</div>
</div>
</nav>
</header>
)}
/>
<Route path="/" exact component={Home} />
<Route path="/apply" exact component={Apply} />
</div>
</Router>
)
}
}
When you click the "Apply" link, it loads the Apply component. In that component, they can receive an error/success notification. From that component is where I want to be able to tell the ReactNotification in App.js what title, message, and type to render. How can I communicate from Apply.js to App.js?
You can pass the addNotification function to your Header component:
<Header addNotification={this.addNotification} />
And you can continue to pass it down to other child components, until you are ready to call it.

Resources