Hide App Elements React - javascript

I have an <App/> component which renders for any page on my site:
const App = () => (
<div>
<Header />
<Main />
<Footer />
<Subfooter />
<SubfooterLegal />
</div>
)
export default App;
The problem I'm having now is that I have a Component (page) which doesn't include any of the components within <App /> aside from <Main /> (which is the router).
I'm puzzled on how to do this, since App.js is the parent component of all components. My only idea of how to do this (possibly) is that when a user clicks a <Link /> to the aforementioned component, I could add setState (maybe?) to App.js and change it to something like hideAppComponents = true and then hide the appropriate components. I know that in this case I would have to make <App /> extends Component since it would then be stateful.
Are there any suggested approaches for a use case like this?

As far as answering your specific question: Yes, adding state to your App and then rendering differently depending on the page would work.
However, a small refactoring of your components would make your problem easier.
In my opinion, a good use of <app> within the context of routing is to just use it to reference which route the user will be on.
<app>
<main>
<Switch>
<Route exact path='/' component={Home}/>
<Route exact path='/about' component={AboutUs}/>
<Route path='/somePageWithoutAFooter' component={CoolPage}/>
</Switch>
</main>
</app>
Now, you have set just a very set of minimal constraints from your top-level app. Depending on the route, you will render a specific child component. So this solves your direct problem. Now you can have CoolPage be its own custom thing, but then the Home page can do something else.
So far, so good. However lets say that both Home and AboutUs have the same basic template of the header and the subfooter that you've been talking about. It would be unfortunate for both of these components to have to describe this architecture inside the render. Instead, you could make a container component like this:
class MyLayout extends Component {
render() {
<div>
<Header />
{this.props.children}
<Footer />
<Subfooter />
<SubfooterLegal />
</div>
}
}
And this component can be used like this:
<MyLayout><Home></MyLayout>
So now, all you need to do is to wrap all of your normal pages in a MyLayout. This can either be done in the app itself, or in a child if it gets more complicated.
Edit: This example uses react-router since this post was tagged with it. You can follow the same principles without using the router if you want. It just makes the <Route> stuff easier to manage.

the only possible solution i can think other than your solution is to use loaction prop. Below is the sample code you can try.
import STORE from './store/STORE';
import {Provider} from 'react-redux';
import {Route, Router} from 'react-router-dom';
import createHashHistory from 'history/createHashHistory';
const history = createHashHistory();
render(
<Provider store={STORE}>
<Router history={history}>
<Route path="/" component={App}/>
</Router>
</Provider>, document.getElementById('app')
);
const App = (location) => (
location.pathname.includes("error") ?
<div>
<Main />
</div> :
<div>
<Header />
<Main />
<Footer />
<Subfooter />
<SubfooterLegal />
</div>
)
export default App;

Related

React Router is giving me a blank page

I am using the react router to create multiple webpages without changing my navbar and all it gives me is a blank page. I have tried multiple things such as a browser router, and switch and neither of them work.
function App() {
return (
<div className="App">
<Navbar />
<Router>
<Link to="/">Home</Link>
<Link to="/aggrid">Aggrid</Link>
<Route path="/" component={GhibliModal} />
<Route path="/aggrid" component={Aggrid} />
</Router>
</div>
);
}```
Well first things first, you need to wrap your whole App component with <BrowserRouter>, but I from what you said in the question, I would assume you already know that.
Secondly, you don't need the <Router> component. Read here.
From reading the documentation, all <Route> components must be wrapped in a <Routes> (note the 's' at the end) component.
And lastly, I'm pretty sure you cannot have <Link> components inside the <Routes> component.
Also, the component prop is now called element, so
<Route path="/" component={GhibliModal} />
should become
<Route path="/" element={<GhibliModal/>} />
You need to add <Outlet /> tag in the components that are loaded by Router.
I usually put it at the end of the JSX:
return (
<div>
<yourcodehere/>
<Outlet/>
</div>
)

Using App component as a home page in react (path "/")

this is my first question here and I apologize upfront if it already been answered. I'm studying react and I started a project as well, and my question is: how can I make my App component a home page? Or do I have to create a component to do so? I´m using react-router-dom for navigation, like the code below, and keep getting the message "No routes matched location "/"". How can I set a route to it? I would like to use the App component instead of using a page component named home. If I did something wrong about the post, again, I'm sorry. Thanks in advance.
import React from 'react'
import {BrowserRouter as Router, Routes, Route, Link} from 'react-router-dom'
import Blog from './pages/Blog'
import About from './pages/About'
import Faq from './pages/Faq'
import Market from './pages/Market'
import GlobalStyle from './styles/global'
function App() {
return (
<Router>
<GlobalStyle/>
<header>
<nav>
<Link to="/products">Nosso produtos</Link>
<Link to="/blog">Diário do Café</Link>
<Link to="/faq">Cafaq - perguntas frequentes</Link>
<Link to="/about">Sobre nós</Link>
</nav>
</header>
<Routes>
<Route path="/products" element={<Market />} />
<Route path="/blog" element={<Blog />} />
<Route path="/faq" element={<Faq />} />
<Route path="/about" element={<About />} />
</Routes>
<footer> Footer </footer>
</Router>
)
}
export default App
The App component is already your default component. Any path will render the App component as long as you have wrapped the App component with the BrowserRouter component
// In index.js
import App from "./App";
import { BrowserRouter } from "react-router-dom";
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<BrowserRouter>
<App />
</BrowserRouter>
);
so I assume your point is to keep the navbar visible regardless of the current path and that is already done because anything placed in the App component will be rendered, and the paths content will be changed based on the elements specified in the Routes.
In case, you want to create a separate Home component, then you will create a Route with a path '/' and the Home Component element.
Make sure that you understand how routing works to avoid any bugs in the future
Hope you found it helpful.
The route element with path ="/" will be your home page
Try with this;
<Route path='/' exact element={<Home/>} />

Routes unable to load using react-router

I'm designing a simple application using create-react-app and I've recently delved into the power of react-router. However, I'm having an issue with pages getting stuck trying to load, and I'm not sure why.
I've got a Navbar component, for which I'll condense the gist of what it is.
import React from 'react';
import { BrowserRouter as Router, Link, Switch, Route } from 'react-router-dom';
import BlogPost from '../Pages/BlogPost';
// Condensed because a lot of the detail is unnecessary and no-one likes blocks of unneeded code
class Navbar extends React.Component {
render() {
return (
<Router>
<nav>
<div id="navigationlinks">
<ul id="navlinks-left">
<li className="nav-item"><Link to='/'>Home</Link></li>
<li className="nav-item"><Link to='/about'>About</Link></li>
</ul>
</div>
</nav>
<Switch>
<Route path='/post' component={BlogPost} />
<Route path='/about'>
<About />
</Route>
</Switch>
</Router>
);
}
}
function About() {
return <h2>The about page.</h2>;
}
export default Navbar;
BlogPost represents a component that is a page in itself. The code looks like this. Again, I'll abstract away from the stuff that's not relevant.
import React from 'react';
import Navbar from '../Components/Navbar';
// Other components on this page. None of them reference the navbar or contain a router of their own.
import BlogBox from '../Sections/BlogBox';
import CommentForm from '../Components/CommentForm';
import CommentBox from '../Sections/CommentBox';
class BlogPost extends React.Component {
getBlogPost(address) {
// Gets blog data (like the title, description, content, image, etc.) using 'fetch' from
// an API at 'address'. Abstracted away because this isn't relevant.
}
componentDidMount() {
console.log("Blog post mounted!");
this.getBlogPost("http://localhost:8080/api/blog/samplepost");
}
render() {
return (
<div className="blog-post">
<Navbar />
<BlogBox post={this.state ? this.state.post : ""}/>
<CommentForm />
<CommentBox comments={this.state ? this.state.comments: ""} />
</div>
);
}
}
export default BlogPost;
The homepage of my application is located at '/'. It's rendered in my index.js file, the code of which is below.
import React from 'react';
import ReactDOM from 'react-dom';
import BlogHome from './Pages/BlogHome';
import BlogPost from './Pages/BlogPost';
ReactDOM.render(
<BlogHome />,
document.getElementById('root')
);
The homepage renders fine, but when I go to navigate to /post, the application attempts to load the page indefinitely, and eventually times out, being unable to do so.
Notice how the BlogPost page component renders the Navbar component, which in turn has a path /post which renders the BlogPost object? I'm not sure if I'm able to change this. Could this be the reason why the /post path can't load?
What concerns me the most here is that I eventually would like to add additional pages which will not only contain this same Navbar, but for which their page links also exist in this Navbar. For example, if I add an About page, this page will not only contain the Navbar, but its link will also be present in this Navbar!
Is there a way I can keep such self-page links in the Navbar, without the recursive render loop occurring?
Issue
You are creating a cycle between rendering Navbar and BlogPost when the current path matches "/post`.
In other words BlogHome renders a Navar which renders a BlogPost which then renders another Navbar and another BlogPost ad nauseam.
Solution
Restructure your navbar and routes a bit to split them out
index.js
Since BlogHome sounds like a page it should be placed on its own route. Move Router here to wrap entire app. Render BlogHome path last as that matches all path prefixes, so it will render if no other route is matched above it by the Switch.
ReactDOM.render(
<Router>
<Switch>
<Route path='/post' component={BlogPost} />
<Route path='/about'>
<About />
</Route>
<Route path="/" component={BlogHome} />
</Switch>
</Router>,
document.getElementById('root')
);
Navbar
Remove the router and routes, leave links only.
class Navbar extends React.Component {
render() {
return (
<nav>
<div id="navigationlinks">
<ul id="navlinks-left">
<li className="nav-item"><Link to='/'>Home</Link></li>
<li className="nav-item"><Link to='/about'>About</Link></li>
</ul>
</div>
</nav>
);
}
}
Now each page should be free to render a Navbar or not.
try to remove Navbar in your BlogPost component, because when the location changes it will switch component here
<Switch>
<Route path='/post' component={BlogPost} />
<Route path='/about'>
<About />
</Route>
</Switch>
and
<nav>
<div id="navigationlinks">
<ul id="navlinks-left">
<li className="nav-item"><Link to='/'>Home</Link></li>
<li className="nav-item"><Link to='/about'>About</Link></li>
</ul>
</div>
</nav>
will persisit.

routing within an app using react router to move to another page

I am trying to use router in my app
so I used react-router-dom, but I am facing issues,
researched and found this link but still not helping me.
Invariant failed: You should not use <Route> outside a <Router>
can you tell me how to use route and link
i need to redirect to another page.
providing my code snippet and sandbox below.
https://codesandbox.io/s/still-smoke-uf731
let Channel = ({ channelName, channelString, onClick, active }) => (
<div onClick={onClick} className=" col-lg-2 col-md-4 col-sm-6 ">
<div>router</div>
<Router>
<Link to={"/here"}> here</Link>
<Switch>
<Route path="/auth" />
<Route path="/" />
</Switch>
</Router>
<div
className="channel-button"
style={{
backgroundColor: active === channelString ? "orange" : ""
}}
>
<p>{channelName}</p>
</div>
</div>
);
Use exact as an attribute in your home route like the following code.
<Router>
<Link to={"/here"}> here</Link>
<Switch>
<Route exact path="/" />
<Route path="/auth" />
</Switch>
</Router>
I checked your sandbox. Looks like a good start, but you messed some things up.
Here is my fork of your sandbox: https://codesandbox.io/embed/staging-fast-rr5k9
First, don't put react components in the containers, put them in the components folder and import them.
What was going on was, that you had brand new <Router> for every page you had. So I pulled the Router out. Its also not imported correctly. It should be
import { BrowserRouter as Router } from "react-router-dom";
So you pretty much need something like this
<div>
<Link to={"/bbc-news"}>BBC</Link>
</div>
<div>
<Link to={"/cnbc"}>CNBC</Link>
</div>
<Switch>
<Route
key={"fbbc-news"}
path="/bbc-news"
render={p => <Channel channelName="BBC" channelString="bbc-news" />}
/>
<Route
key={"cnbc"}
path="/cnbc"
render={p => <Channel channelName="CNBC" channelString="cnbc" />}
/>
</Switch>
</Router>
Where Channel component renders whats inside the channel. the key in Route is important, because it makes React properly trigger componentDidMount, which calls the thunk action which fetches (that one is perfect).
Then to access the results from fetch, which you have placed in Redux =>
const mapStateToProps = state => ({ json: state.json });
You don't need a lot of the things you had, so I have removed them, like the onClick, which was trying to do react routers job
You can try this:
import Stats from './containers/stats';
<Route
exact={true}
path="/"
component={Stats}
key="Mykey"
/>

How to use routes in two different components - ReactJS

I am creating an application using ReactJS. I am using react router v4 from react-router-dom.
I have written routes in index.js file.
<BrowserRouter>
<Switch>
<Route exact path="/" component={Login} />
<Route exact path='/dashboard' component={Viewport} />
</Switch>
</BrowserRouter>
Rest of the application in Viewport.js file.
return (
<div className="">
<Sidebar navigation={this.viewport} />
<HeaderBanner user={this.props.user} />
<div className="center-panel">
//todo
//Can I use router here?
</div>
</div>
)
After user login's, I am rendering Viewport which contains Sidebar and header bar by default. Based on the item click in the sidebar navigation, I need to render components dynamically. As of now, if I write anything in the place of todo, it renders only that component for the complete browser window.
Is there any way to use routers in multiple places of the application? If yes, how can I implement it? If no, what's the best solution?
As far as I have seen, routers will be stacked at one place in the application.
Thanks in advance.
I followed a tutorial on youtube recently which was very useful
So I took some of it and applied it to your setup
<BrowserRouter>
<div>
<Route exact path="/" component={Login} />
<Route exact path='/dashboard' component={Viewport} />
</div>
</BrowserRouter>
import { NavLink, Route } from 'react-router-dom';
class Viewport extends Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<div className="Side-bar">
<NavLink
activeClassName="active"
to={`${this.props.match.url}/sub-page-name-1`}>Sub Page 1</NavLink>
<NavLink
activeClassName="active"
to={`${this.props.match.url}/sub-page-name-2`}>Sub Page 2</NavLink>
<NavLink
activeClassName="active"
to={`${this.props.match.url}/sub-page-name-3`}>Sub Page 3</NavLink>
</div>
<HeaderBanner user={this.props.user} />
<div className="center-panel">
<Route path={`${this.props.match.url}/sub-page-name-1`} component={SubPagePanel1} />
<Route path={`${this.props.match.url}/sub-page-name-2`} component={SubPagePanel2} />
<Route path={`${this.props.match.url}/sub-page-name-3`} component={SubPagePanel3} />
</div>
</div>
)
}
}
I removed Switch as well because I didn't use it for my sub pages... :-S
Update: Have created a repo showing a working example of sub page content
https://github.com/PocketNinjaDesign/so-sub-routes-answer
Yes you can use <Routes> in as many places as you want. <Router> components are the ones you can only use once.

Categories

Resources