Content not rendered on webpage, React JS - javascript

I am trying to render the h1 tag when following the path '/', however, when I refresh the page the text doesn't show up. I have already switched the tags with tags as I was following an old tutorial. I am using react-router-dom v6.
HomePage.Js
import React, { Component } from "react";
import RoomJoinPage from "./RoomJoinPage";
import CreateRoomPage from "./CreateRoomPage";
import { BrowserRouter as Router, Routes, Route, Link, Redirect } from "react-router-dom";
export default class HomePage extends Component {
constructor(props) {
super(props);
}
render() {
return (
<Router>
<Routes>
<Route path='/'>
<h1>This is the home page</h1>
</Route>
<Route path='/join' element={ <RoomJoinPage /> } />
<Route path='/create' element={ <CreateRoomPage/> } />
</Routes>
</Router>
);
}
}
App.Js
import React, { Component } from "react";
import { render } from "react-dom";
import HomePage from "./HomePage";
export default class App extends Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<HomePage />
</div>
);
}
}
const appDiv = document.getElementById("app");
render(<App />, appDiv);

set your routing in app.js like this
<Router>
<Switch>
<Route exact path='/'>
<h1>This is the home page</h1>
</Route>
<Route exact path='/join'> </Route>
<Route exact path='/create'> </Route>
</Switch>
</Router

Related

ReactJS Imports not working blank webpage

I am a beginner learning ReactJS and was trying to make a full-stack quiz web application using DjangoRestFramework+ReactJS.
The Problem
I am not seeing anything rendering to my webpage when I try using imports. I am not getting any errors, but my web page is blank.
My Files
Here is my App.JS.
import { render } from "react-dom";
import HomePage from "./HomePage";
import GameJoinPage from "./GameJoinPage";
export default class App extends Component {
constructor(props) {
super(props);
}
render() {
return (
<HomePage />
);
}
}
const appDiv = document.getElementById("app");
render(<App />, appDiv);
My Index.html
<! DOCTYPE html>
<html>
<head>
<meta charset="UTF-9">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Quiz App</title>
{% load static %}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link
rel="stylesheet"
href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap"
/>
<link rel="stylesheet" type="text/css" href="{% static "css/index.css" %}"
/>
</head>
<body>
<div id="main">
<div id="app">
</div>
</div>
<script src="{% static "frontend/main.js" %}"></script>
</body>
</html>
And my HomePage file
import React, { Component } from "react";
import GameJoinPage from "./GameJoinPage";
import CreateRoomPage from "./CreateGamePage";
import {
BrowserRouter as Router, Switch, Route, Link, Redirect} from "react-router-dom";
export default class HomePage extends Component {
constructor(props) {
super(props);
}
render(){
return (
<Router>
<Switch>
<Route exact path="/"><p>This is the home page</p></Route>
<Route path="/join" component={GameJoinPage} />
<Route path="/create" component={CreateGamePage} />
</Switch>
</Router>
);
}
}
What I tried
When I put <h1>Hello World</h1> in place of <HomePage \>, It rendered the Hello World to the webpage as expected.
But when I put the <HomePage \> or any other tag such as <CreateGamePage \> In App.js, nothing renders to the webpage. I am not getting any errors on Webpack compilation.
Try with id #main
const appDiv = document.getElementById("main");
and just change HomePage.js to check
<Switch>
<Route exact path="/" render={()=> <h2>render default page</h2>}/>
<Route path="/join" component={GameJoinPage} />
<Route path="/create" component={CreateGamePage} />
</Switch>
Add router to the parent element
import { render } from "react-dom";
import HomePage from "./HomePage";
import GameJoinPage from "./GameJoinPage";
import { BrowserRouter as Router } from "react-router-dom";
export default class App extends Component {
constructor(props) {
super(props);
}
render() {
return (
<Router>
<HomePage />
</Router>
);
}
}
const appDiv = document.getElementById("app");
render(<App />, appDiv);
Change the HomePage file to
import React, { Component } from "react";
import GameJoinPage from "./GameJoinPage";
import CreateRoomPage from "./CreateGamePage";
import { Switch, Route, Link, Redirect } from "react-router-dom";
export default class HomePage extends Component {
constructor(props) {
super(props);
}
render() {
return (
<Switch>
<Route exact path="/" render={() => <p>This is the home page</p>} />
<Route path="/join" component={GameJoinPage} />
<Route path="/create" component={CreateGamePage} />
</Switch>
);
}
}
I figured it out! The issue was not with my code, it was a misspelling in my HomePage.js file. I was trying to import CreateRoomPage from CreateGamePage when in fact in CreateRoomPage did not exist, the correct one was CreateGamePage. Thank you all for the helpful responses!
Before
HomePage.JS
import React, { Component } from "react";
import GameJoinPage from "./GameJoinPage";
import CreateGamePage from "./CreateGamePage"; // Now its correct!
import { Switch, Route, Link, Redirect } from "react-router-dom";
export default class HomePage extends Component {
constructor(props) {
super(props);
}
render() {
return (
<Switch>
<Route exact path="/" render={() => <p>This is the home page</p>} />
<Route path="/join" component={GameJoinPage} />
<Route path="/create" component={CreateGamePage} />
</Switch>
);
}
After
import React, { Component } from "react";
import GameJoinPage from "./GameJoinPage";
import CreateRoomPage from "./CreateGamePage";
import { Switch, Route, Link, Redirect } from "react-router-dom";
export default class HomePage extends Component {
constructor(props) {
super(props);
}
render() {
return (
<Switch>
<Route exact path="/" render={() => <p>This is the home page</p>} />
<Route path="/join" component={GameJoinPage} />
<Route path="/create" component={CreateGamePage} />
</Switch>
);
}

React not displaying correct route

I am putting together a small application to get used to React, now I have installed React-Router-Dom and when I click a link the URL correctly changes. The issue is that the correct Component does not display.
index.js
ReactDOM.render(
<Router>
<App />
</Router>,
document.getElementById('root')
);
registerServiceWorker();
App.js
import React, { Component } from 'react';
import Sidebar from './Components/Sidebar';
import SidebarItem from './Components/SidebarItem';
import Home from './Components/Home';
import './App.scss';
import { Link, Route, Switch } from 'react-router-dom';
class App extends Component {
constructor() {
super();
this.state = {};
}
render() {
return (
<div className="App">
<Link to='/home'>Home</Link>
<Switch>
<Route path='/home' Component={Home} />
</Switch>
</div>
);
}
}
export default App;
Can anyone tell me the reason why HomeComponent does not appear?
The prop of the Route that takes a component is spelled component with a small c, not Component.
Example
function Home() {
return <div> Home </div>;
}
class App extends Component {
render() {
return (
<Router>
<div>
<Link to="/home">Home</Link>
<Switch>
<Route path="/home" component={Home} />
</Switch>
</div>
</Router>
);
}
}

Render nested route component on new page

I want to be able to have a Portfolio page (example.com/portfolio), and a dynamic route for individual case studies (example.com/portfolio/case-study/dynamic-url-slug). Currently, the new component that should render in its own page is still rendering within the page (understandable, as the markup declares the route within the containing div). But how do I get it to render on its own page?
App.js (where all routes are declared)
import React, { Component } from 'react';
import { Switch, Route } from 'react-router-dom';
import Home from './components/Pages/Home/Home';
import About from './components/Pages/About/About';
import Portfolio from './components/Pages/Portfolio/Potfolio';
import CaseStudy from './components/Pages/Portfolio/CaseStudyPage';
export default class App extends Component {
render() {
return (
<div className="icon-container" id="outer-container">
<div className="pages">
<Switch>
<Route exact path='/' component={ Home } />
<Route path='/about' component={ About } />
<Route path='/portfolio' component={ Portfolio } />
<Route exact path={`/portfolio/case-study/:caseSlug`}
render={(props) => <CaseStudy />} />
</Switch>
</div>
</div>
)
}
}
Portfolio.js
import React, { Component } from 'react';
import '../styles/vendor/swiper/swiper.min.css';
import Swiper from 'react-id-swiper';
import { Link, Route } from 'react-router-dom';
import CaseStudyPage from './Pages/Work/CaseStudyPage';
const case_studiesURL = "http://myprivateblogapi.com/wp-json/wp/v2/case_studies?_embed";
const case_URL = '/portfolio/case-study/';
export default class Portfolio extends Component {
constructor(props) {
super(props);
this.state = {
case_studies: [],
isLoading: true,
requestFailed: false
}
}
componentDidMount() {
fetch(case_studiesURL)
{/* fetching all the appropriate data */}
}
renderPortfolioItem(data) {
return props => <CaseStudyPage data={data} {...props} />
}
render() {
if(this.state.isLoading) return <span>Loading...</span>
const params = {
{/* swiper parameters */}
}
let case_studies_items = this.state.case_studies.map((case_studies_item, index) => {
return (
<div className="portfolio-slide" id={`swiper-slide-${index}`}
key={index}
>
<Link className="portfolio-link"
to={`${case_URL}${case_studies_item.slug}`}>
<h3 className="portfolio-swiper--slide-title"> {case_studies_item.title.rendered}</h3>
</Link>
<Route exact path={`${case_URL}:caseSlug`}
render={this.renderPortfolioItem(case_studies_item)} />
</div>
)
});
return(
<div className="portfolio-swiper--container">
<Swiper {...params}>
{case_studies_items}
</Swiper>
</div>
)
}
}
You should define a route for each different views in react router,
<Switch>
<Route exact path='/' component={ Home } />
<Route exact path='/about' component={ About } />
<Route exact path='/portfolio' component={ Portfolio } />
<Route exact path='/portfolio/case-study' component={ CaseStudy } />
<Route exact path='/portfolio/case-study/:caseSlug' component {CaseStudyDetails} />
</Switch>
and you don't need to create a render method to pass props to your view components. You can easily reach router props inside of a react component if it is already rendered into Router,
this.props.match
this.props.location
this.props.history
as an example you can get your dynamic parameter inside of CaseStudy component like,
this.props.match.caseSlug

React Router Won't Work Without Refresh

Basically, the Route component will not trigger on the click of a Link that changes the path; but after a refresh, the correct component is shown. What could solve the issue?
App component:
import React, { Component } from 'react';
/**
* Import Router
*/
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
/**
* Import custom components
*/
import IndexComponent from '../components/index_component';
import LoginComponent from '../components/login_component';
/**
* Import containers
*/
import Navbar from '../containers/Navbar';
import Footer from '../containers/Footer';
export default class App extends Component {
render() {
return (
<div>
<Navbar />
<Router>
<Switch>
<Route path="/login" component={LoginComponent} />
<Route path="/" component={IndexComponent} />
</Switch>
</Router>
<Footer />
</div>
);
}
}
Login Component:
import React, { Component } from 'react';
class LoginComponent extends Component {
render() {
return (
<div>LOGIN COMP</div>
);
}
}
export default LoginComponent;
You should enclose all your components inside <Router> that will solve your issue.
<Router>
<Navbar />
<Switch>
<Route path="/login" component={LoginComponent} />
<Route path="/" component={IndexComponent} />
</Switch>
<Footer />
</Router>
Try the following solution:
import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import IndexComponent from '../components/index_component';
import LoginComponent from '../components/login_component';
<Router>
<Switch>
<Route path="/login" component={LoginComponent} />
<Route path="/" component={IndexComponent} />
</Switch>
</Router>

Declaring React Routes in a separate file and Importing

I am new to React. I have been trying to declare routes in a file and then use it in another file.
Here is my routes.js
import React from 'react';
import { Route } from 'react-router-dom';
import App from './components/App';
import Template1 from './components/template1';
import Template2 from './components/template2';
import Template3 from './components/template3';
const routes = (
<Route exact path="/" component={App}>
<Route exact path="/sessionstate1" component={Template1} />
<Route exact path="/sessionstate2" component={Template2} />
<Route exact path="/sessionstate3" component={Template3} />
</Route>
)
export default routes
and index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router } from 'react-router-dom';
import './styles/css/index.css';
import routes from './routes.js';
ReactDOM.render(
<Router history={browserHistory} routes={routes} />,
document.getElementById('root')
);
I am not getting any errors or warning but the page is not loading. Please tell me what I am missing
Thanks
well i had the same issue a few days ago, and the solution for me was this...
This one of the routes files:
import React from 'react';
import { Route } from 'react-router-dom';
import { ComponentY } from '../components/functionalitys';
export default [
<Route path="/appointment" component={ComponentY} exact key="create" />,
];
This another route file:
import React from 'react';
import { Route } from 'react-router-dom';
import { LoginPage, Register } from '../components/user';
export default [
<Route path="/register" component={Register} exact key="create" />,
<Route path="/login" component={LoginPage} exact strict key="login" />
];
And this is how I imported in the main app.js:
import routesFromFile1 from './the/route';
import routesFromFile2 from './the/other/route';
class App extends Component{
render(){
return(
<div className="wrapper">
<section className="content container-fluid">
<Switch>
<Route exact path="/" component={Home} strict={true} exact={true}/>
<Route path="/500" component={InternalServer} />
{routesFromFile1}
{routesFromFile2}
</Switch>
</section>
</div>
)
}
}
I hope this help Someone! Cheers!!
You don't need to wrap your Routes inside a div. Try something like this:
routes.js
import React from 'react';
import { Router, Route } from 'react-router';
import { Template1, Template2, Template3 } from './templates';
const createRoutes = () => (
<Router>
<Route exact path="/sessionstate1" component={Template1}/>
<Route exact path="/sessionstate2" component={Template2}/>
<Route exact path="/sessionstate3" component={Template3}/>
</Router>
);
export default createRoutes;
index.js
import ReactDOM from 'react-dom';
import createRoutes from './routes';
const routes = createRoutes();
ReactDOM.render(
routes,
document.getElementById('root')
);
index.js:
import LoginRoutes from './login/routes'
let routeConfig = [];
routeConfig = routeConfig.concat(LoginRoutes(store));
<Router routes={routeConfig}/>
routes.js:
export default (store) => {
return [
{path: '/login', component: Login},
{path: '/signup', component: SignUp},
]
}
This way you can add routes from different files and spread your route definitions to different folders that serve the contextual purpose of the route.
The store variable is there in case you want to use redux and want to have an onEnter event on the route. Example:
export default () => {
const sessionEnter = (location) => {
let {appId} = location.params;
store.dispatch(loadApp(appId));
return [
{path: '/apps/:appId', component: App, onEnter: sessionEnter},
]
}
I find onEnter events a good alternative to componentDidMount, data-fetching-wise. Invoking a data fetch on route level makes more sense to me as I see the component as part of the presentation level.
I think the problem is with wrapping the Route inside a div.
Try wrapping them inside a Route like following. Try this fiddle and change the routes wrapper to div.
const routes=(
<Route >
<Route exact path="/sessionstate1" component={Template1}/>
<Route exact path="/sessionstate2" component={Template2}/>
<Route exact path="/sessionstate3" component={Template3}/>
</Route >
)
export default routes;
And import it into index.js
import routes from './routes.js';
ReactDOM.render(
<Router history={browserHistory} routes={routes} />,
document.getElementById('root')
);
With Typescript
Sepate the file for routes as routes.ts
export const routes = [
{ path: '/', component: Home },
{ path: '/auth-callback', component: authCallback },
{ path: '/fetch-data/:startDateIndex?', component: FetchData }
];
In the App.tsx
export function App() {
const routeComponents = routes.map(({ path, component }, key) => <Route exact path={path} component={component} key={key} />);
return (
<Layout>
{routeComponents}
</Layout>
);
}
Layout.tsx
export default (props: { children?: React.ReactNode }) => (
<React.Fragment>
<div>
<NavMenu />
<TopAppBarFixedAdjust>
{props.children}
</TopAppBarFixedAdjust>
</div>
</React.Fragment>
);
I know I'm little late but here my working
here a working demo
my dependencies are
"react": "16.2.0",
"react-dom": "16.2.0",
"react-router-dom": "4.2.2",
"react-scripts": "1.1.0"
create nav.js file as this
this file is responsible for storing all the links for navbar
import React, { Component } from "react";
import { Link } from "react-router-dom";
class Navi extends Component {
render = () => (
<div>
<Link to="/">Go to Home</Link> <br />
<Link to="/about">Go to About</Link> <br />
<Link to="/any-route">404 page</Link>
</div>
);
}
export default Navi;
Then the routes.js file
here you will define all your routes, and your pages where the routes should navigates to
import React, { Component } from "react";
import { BrowserRouter as Router, Route, Link, Switch } from "react-router-dom";
// your components
const Home = () => <h1>Home</h1>;
const About = () => <h1>About</h1>;
const MissingPage = () => <h1>404</h1>;
const routes = (
<Switch>
<Route path="/" exact component={Home} />
<Route path="/about" component={About} />
<Route component={MissingPage} />
</Switch>
);
export default routes;
finally here is the code for index.js
import React, { Component } from "react";
import ReactDOM from "react-dom";
import { BrowserRouter as Router, Route, Link, Switch } from "react-router-dom";
import Navi from "./nav";
import routes from "./routes";
// initialize rotues and navi links
const initRoutes = () => (
<Router>
<div>
<Navi />
{routes}
</div>
</Router>
);
const initializedRoutes = initRoutes();
ReactDOM.render(
initializedRoutes,
document.getElementById("root")
);
This is the routing page created
routing page imported
Hope, it will help everyone. click the link to see code.!!
In react-router-dom version 6.x.x
Suppose you have the following URLs in your react app
/
/home
/handlers
/handlers/notes
/handlers/users
you can isolate all routing components related to handlers(including its nested URLs) by:
Define your main routing
<BrowserRouter>
<Routes>
<Route path="/" element={<HomePage />} />
<Route path="/home" element={<HomePage />} />
<Route path="/handlers/*" element={<AllHandlersPages />} />
</Routes>
</BrowserRouter>
Notice the existence of path="/handlers/*" where we have a wildcard * to tell react-router-dom to match with any nested route too
then
declare AllHandlersPages in another file like this
export function AllHandlersPages() {
return (
<Routes>
<Route>
<Route index element={<HandlersIndexPage />} />
<Route path="notes" element={<NotesPage />} />
<Route path="users" element={<UsersPage />} />
</Route>
</Routes>
);
}
Because <Route /> can't be defined unless it has a parent <Routes /> don't forget to make them nested properly.
Full working Demo
Try it like this way
import React from "react";
import {HashRouter as Router, Route} from 'react-router-dom';
import NoteContainer from "./component/note/index.jsx";
import Header from "./component/common/header.jsx";
const App = (props) => {
return (
<div className="container">
<Header/> {props.children}
</div>
);
};
var x = () => {
return (
<h1>Hello world!</h1>
);
};
module.exports = () => {
return (
<Router>
<App>
<Route path="/" component={NoteContainer}/>
<Route path="/inbox" component={x}/>
</App>
</Router>
);
};
I did it with very simple way. Follow the two steps below.
In App.js
import "bootstrap/dist/css/bootstrap.min.css";
import Header from "./component/common/header";
import { BrowserRouter as Router, Route, Link, Switch } from "react-router-dom";
import routes from "./routes";
function App() {
return (
<Router>
<section className="container">
<Header />
{routes}
</section>
</Router>
);
}
export default App;
in routes.js
import React, { Component } from "react";
import { BrowserRouter as Router, Route, Link, Switch } from "react-router-dom";
import Overview from "./component/overview/overview";
import UsersList from "./component/userslist/UsersList";
import FavUserList from "./component/userslist/FavUserList";
const routes = (
<Switch>
<Route exact path="/" component={Overview} />
<Route path="/adduser" component={UsersList} />
<Route path="/favuser" component={FavUserList} />
</Switch>
);
export default routes;
Note: Make sure you import like this
import { BrowserRouter as Router, Route, Link, Switch } from "react-router-dom";
In < Header /> component you have to declare navigation link.
i'm starting into react too, and i figured out a way to make what you are looking for.
What i did was inside the app file (which comes default in every project) i imported the routes file, the routes file is located in a folder called approuter (you can name it whatever you want), i'll write some of my code so you can see what i mean
//APP FILE
import AppRouter from './router/approuter'
function App() {
return (
<>
<div className='app' id="mode">
<AppRouter />
</div>
</>
)
}
export default App
//ROUTER FILE/
import { Route, Routes } from 'react-router-dom'}
import Register from "../pages/register"
import Login from "../pages/login"
export default function AppRouter() {
return (
<>
<div>
<Routes>
<Route path="login" element={<Login />}/>
<Route path="register" element={<Register />}/>
</Routes>
</div>
</>
)
}
This actually worked in a project i'm currently working on, i hope this can answer your question
**index.js**
import ReactDOM from "react-dom/client";
import Paths from "./routes/Paths";
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<React.StrictMode>
<Paths />
</React.StrictMode>
);
**Paths.js**
import LoginSample from "../portal/LoginSample";
import Dashboard from "../portal/Dashboard";
function Paths() {
return (
<Router>
<Routes>
<Route path="/" element={<LoginSample />} />
<Route path="/dashboard" element={<Dashboard />} />
</Routes>
</Router>
);
}
export default Paths;
Also new to react and was running into the same issue. Here is what I tried (obviously different code and structure, but what we're looking for should be the same functionality)
index.js
import React from "react";
import ReactDOM from "react-dom";
import { createHashHistory } from "history";
import { BrowserRouter, Route } from 'react-router-dom';
import routes from "./routes";
const allRoutes = routes;
ReactDOM.render(
allRoutes,
document.getElementById("app")
)
and the routes.js file.
import React from "react";
import { createHashHistory } from "history";
import { BrowserRouter, Route } from 'react-router-dom';
import App from "./pages/App";
import Detail from "./pages/Detail";
import List from "./pages/List";
const routes = (
<BrowserRouter>
<div>
<Route exact path="/" component={ App } />
<Route path="/" component={ List } />
<Route path="/detail/:repo" component={ Detail } />
</div>
</BrowserRouter>
);
export default routes;
Let me know if that works for you.

Categories

Resources