Why react is not rendering anything using router? - javascript

When I try to display the elements, I can't display anything, even with the <Link to=""> working fine.
I want a simple navbar using react-router-dom, to make a multiple pages web app.
I hope this error can be solved without any advanced code, cause I'm trying to learn the basics of React first.
App.js:
import './App.css';
import { useEffect, useState } from "react"
import axios from 'axios';
import React from "react"
import {
BrowserRouter as Router,
Routes,
Route,
Link
} from "react-router-dom"
import home from './home'
import userlist from './userlist'
function App() {
return (
<body>
<header>
<div className="divheadertitle">
<h1 className="headertitle">Tree.io</h1>
</div>
<Router>
<nav>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/userlist">User list</Link></li>
</ul>
</nav>
</Router>
<Router>
<Routes>
<Route path='/userlist' element={<userlist />} />
<Route path='/' element={<home />} />
</Routes>
</Router>
</header>
</body>
)
}
export default App;
userlist.js:
import React from "react"
import axios from 'axios'
import { useState, useEffect } from "react"
const userlist = () => {
const [listOfUsers, setListOfUsers] = useState([])
useEffect(() => {
axios.get('https://localhost:3001/userlist')
.then((response) => {
setListOfUsers(response.data)
})
})
return (
<div className="userlistdiv">
<h1>Lista de usuários:</h1>
{listOfUsers.map((user) => {
return(
<div className="userdiv">
<h1>Name: {user.name}</h1>
<h1>Age: {user.age}</h1>
<h1>E-mail: {user.email}</h1>
</div>
)
})}
</div>
)
}
export default userlist;

The links are rendered into a different router than the routes. React components are also Capitalized. Move all the links and routes into the same router.
import Home from './home'
import Userlist from './userlist'
function App() {
return (
<body>
<header>
<div className="divheadertitle">
<h1 className="headertitle">Tree.io</h1>
</div>
<Router>
<nav>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/userlist">User list</Link></li>
</ul>
</nav>
<Routes>
<Route path='/userlist' element={<Userlist />} />
<Route path='/' element={<Home />} />
</Routes>
</Router>
</header>
</body>
);
}
Additionally, the Userlist component is unconditionally fetching data and updating state, this is likely leading to some render looping. Add a dependency array.
useEffect(() => {
axios.get('https://localhost:3001/userlist')
.then((response) => {
setListOfUsers(response.data)
});
}, []); // <-- empty dependency array to run once on mount

Try this instead of function in your map method:
{
listOfUsers.map((user) =>(
<div className="userdiv">
<h1>Name: {user.name}</h1>
<h1>Age: {user.age}</h1>
<h1>E-mail: {user.email}</h1>
</div>
))
}
and make sure your api send your response truthly.
If you want to run an effect and clean it up only once, you can pass an empty array [ ] as dependency
I hope all of these be useful for you

Related

HTML not showing up on React webpage [duplicate]

This question already has an answer here:
react-router-dom v6 Routes showing blank page
(1 answer)
Closed 18 hours ago.
So as the title suggests, Im looking for a reason as to why my webpage is not showing up on the website
Here is the App.js file
import { useState, useEffect } from "react";
import { BrowserRouter as Router, Routes, Route, Link } from "react-router-dom";
import axios from "axios";
import Post from "./Post.js";
function App() {
const [posts, setPosts] = useState([]);
useEffect(() => {
axios.get("https://jsonplaceholder.typicode.com/posts").then((response) => {
setPosts(response.data);
});
}, []);
return (
<Router>
<div>
<nav>
<ul>
<li>
<Link to="/">All Posts</Link>
</li>
</ul>
</nav>
<Routes>
<Route path="/" exact>
<h1>All Posts</h1>
<ul>
{posts.map((post) => (
<li key={post.id}>
<Link to={`/posts/${post.id}`}>{post.title}</Link>
</li>
))}
</ul>
</Route>
<Route path="/posts/:id">
<Post />
</Route>
</Routes>
</div>
</Router>
);
}
export default App;
I made Post.js a separate js file from App like this:
import { useState, useEffect } from "react";
import axios from "axios";
function Post() {
const [post, setPost] = useState(null);
const id = window.location.pathname.split("/")[2];
useEffect(() => {
axios.get(`https://jsonplaceholder.typicode.com/posts/${id}`).then((response) => {
setPost(response.data);
});
}, [id]);
if (!post) {
return <div>Loading...</div>;
}
return (
<div>
<h1>{post.title}</h1>
<p>{post.body}</p>
</div>
);
}
export default Post;
The site is running as well. I can access everything that is there, but for some reason, it is just a blank page.
I hope you can help me with this issue. Thank you
You cannot directly put the content to be rendered under <Route>. Instead, set the element attribute on the <Route>.
For example:
<Route path="/posts/:id" element={<Post/>}/>
You also need to extract the content for all posts into a separate component.
<Route path="/" element={<AllPosts/>}>

React Dom Routes not working as intended, changes the path but nothing on the page

I am making a webplatform working with the OpenLibrary API, I am pulling data from the subjects then when you click on one of the books in the subjects, I want to be taken to a page called 'Book' where I display the data.
Now I have set up my Routes (i think they're correct), but when I click one of the items in the list, it doesn't do anything, it changes the URL to the route I set up, but it doesn't take me to the Book component where I display the data. Now, I haven't posted my Book.js file because it just has test code in it to see if I can get to the component. Any help will be appreciated!
Here are some snippets of my code:
App.js:
import React, { useState, useEffect } from "react";
import axios from "axios";
import Works from "./components/Works";
import Navbar from "./components/Navbar";
import Footer from "./components/Footer";
import "./styles.css";
function App() {
const [subjects, setSubjects] = useState([]);
const [worksDetails, setWorkDetails] = useState([]);
const [isLoading, setIsLoading] = useState(false);
const url = "https://openlibrary.org/subjects/animals.json?limit=10";
useEffect(() => {
axios
.get(url)
.then((response) => {
setSubjects(response.data);
setWorkDetails(response.data.works);
setIsLoading(true);
})
.catch((error) => {
console.log(error);
});
}, []);
if (!isLoading) {
return <p>Loading...</p>;
} else {
return (
<>
<Navbar />
<div className="contentHeader">
<h1 className="subjectHeader" style={{ padding: "10px" }}>
Subject: {subjects.name.toUpperCase()}
</h1>
<h1 className="workHeader" style={{ padding: "10px" }}>
Work Count: {subjects.work_count.toLocaleString()}
</h1>
</div>
<div>
<Works works={worksDetails} />
</div>
<Footer />
</>
);
}
}
export default App;
Works.js
import React from "react";
import { Link } from "react-router-dom";
import Book from "../routes/Book";
const Works = (props) => {
return (
<div className="container">
<div>
<div className="heading">
{props.works.map((work) => {
return (
<Link to={`/book/${work.key}`} element={<Book />} key={work.key}>
<ul>{work.title}</ul>
</Link>
);
})}
</div>
</div>
</div>
);
};
export default Works;
Index.js
import { createRoot } from "react-dom/client";
import "./index.css";
import { BrowserRouter, Routes, Route } from "react-router-dom";
import App from "./App";
import Book from "./routes/Book";
const rootElement = document.getElementById("root");
const root = createRoot(rootElement);
root.render(
<BrowserRouter>
<Routes>
<Route path="*" element={<App />} />
<Route path="/book" element={<Book />}>
<Route path=":bookId" element={<Book />} />
</Route>
</Routes>
</BrowserRouter>
);
Issue
When you use
<Route path="/book" element={<Book />}>
<Route path=":bookId" element={<Book />} />
</Route>
The Route component is expecting Book to render an Outlet component for the nested Route component. This doesn't appear to be the UX you are going for though. The outer route is matched and rendered, but then because there's no outlet the inner route rendering the actual Book component you want with the param isn't rendered at all.
It turns out that in the fetched data that work.key isn't just an id, but a nested route value it seems, i.e. something like "key": "/works/OL138052W", so the UI is computing a malformed route ("/book//works/OL138052W") and linking to a route that doesn't exist.
Solution
to={`/book${work.key}`} is the path you are linking to, note the removal of the "/" between "book" and the injected work.key value:
<Link key={work.key} to={`/book${work.key}`}>
<ul>{work.title}</ul>
</Link>
Then the should render one of the following:
<Route path="/book/works/:bookId" element={<Book />} />
or
<Route path="/book/works">
<Route path=":bookId" element={<Book />} /> // "/book/works/:bookId"
</Route>
If you don't want to mess with this work.key value then you may want to select one of the other properties, so long as they provide sufficient uniqueness for identification purposes.
I believe your Route should look like this:
<Route path="/book/:bookId" element={<Book />}>

React Js: <Link/> not working after build in gh-pages or netlify

I've built a react front end for my rest api. I've got them both deployed! However my navbar component has tags and do not work after clicking on them once. This happens in both netlify and gh-pages. Has anyone encountered this solution before? I am using HashRouter instead of ReactRouter. Thanks for taking your time with this :)
import React from "react";
import { Link } from "react-router-dom";
export default ({ context }) => {
const authedUser = context.authenticatedUser;
//Nav bar conditionally rendered on if the user is logged in or not
return (
<div>
<div className="header-div">
<div>
<Link to="/" className="header-div-left">
Student Courses
</Link>
</div>
<nav>
{authedUser ? (
<React.Fragment>
<div className="header-div-right">
<span className="header-div-right">
Welcome {authedUser.firstName} {authedUser.lastName}
</span>
<Link className="header-div-right" to="/signout">
Sign Out
</Link>
</div>
</React.Fragment>
) : (
<React.Fragment>
<div className="header-div-right-up-in">
<Link className="header-div-right" to="/signup">
Sign Up
</Link>
<Link className="header-div-right" to="/signin">
Sign In
</Link>
</div>
</React.Fragment>
)}
</nav>
</div>
</div>
);
};
import React from 'react';
import {
HashRouter as Router,
Route,
Switch
} from 'react-router-dom';
import './App.css';
import CourseDetail from './components/CourseDetail';
import Courses from './components/Courses';
import CreateCourse from './components/CreateCourse';
import Header from './components/Header';
import UpdateCourse from './components/UpdateCourse';
import UserSignIn from './components/UserSignIn';
import UserSignOut from './components/UserSignOut';
import UserSignUp from './components/UserSignUp';
import NotFound from './components/NotFound';
import PrivateRoute from './PrivateRoute';
import withContext from './Context';
//Connecting the SignUp & SignIn to context.
//This shares the data and actions throughout the component tree
/* Adding the const's as the component to the route handler
lets the components UserSignIn & UserSignUp gain access to
the function in context and any data or actions passed into
<Context.Provider value={value}> */
const UserSignInWithContext = withContext(UserSignIn);
const UserSignUpWithContext = withContext(UserSignUp);
const UserSignOutWithContext = withContext(UserSignOut);
/* To let the user know they are signed in
need to make changes to the name display in the end header */
const HeaderWithContext = withContext(Header);
const CoursesWithContext = withContext(Courses);
const CourseDetailsWithContext = withContext(CourseDetail);
const UpdateCourseWithContext = withContext(UpdateCourse)
const CreateCourseWithContext = withContext(CreateCourse)
export default () => (
<Router>
<div >
<HeaderWithContext/>
<Switch>
<Route exact path="/" component={CoursesWithContext} />
<PrivateRoute path="/courses/create" component={CreateCourseWithContext} />
<Route exact path="/courses/:id" component={CourseDetailsWithContext} />
<PrivateRoute path="/courses/:id/update" component={UpdateCourseWithContext} />
<Route path="/signin" component={UserSignInWithContext} />
<Route path="/signup" component={UserSignUpWithContext} />
<Route path="/signout" component={UserSignOutWithContext} />
<Route component={NotFound} />
</Switch >
</div >
</Router>
);

React Router URL Change but Not Component

React Router change the URL but the component is not rendered
I have already looked for answer but none of those example is worked
Current React Router & React Router DOM version is 5.0.0
It's still plain create-react-app
I've tried to use Switch tag
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';
const Index = () => {
return <h2>Home</h2>;
};
const About = () => {
return <h2>About</h2>;
};
const Users = () => {
return <h2>Users</h2>;
};
class App extends Component {
render() {
return (
<Router>
<div className="App">
<header className="App-header">
<li>
<Link to="/">
<h1>Home</h1>
</Link>
</li>
<li>
<Link to="/about">
<h1>About</h1>
</Link>
</li>
<li>
<Link to="/users">
<h1>Users</h1>
</Link>
</li>
</header>
<hr />
<Route exact path="/" Component={Index} />
<Route path="/about" Component={About} />
<Route path="/users" Component={Users} />
</div>
</Router>
);
}
}
export default App;
It wont render the component
Try setting the 'component' attribute with lowercase c
I think it's a simple mistake. You capitalized the attribute word component in your Routes.

Child component not rendering with React Router v4

I am trying my hands on React Nested routing & this is my how my app looks like
Posts.js (Parent (plural) Component) which is rendering fine.
import React from "react";
import { Route } from "react-router-dom";
import Post from "./Post";
import { Link, Switch } from "react-router-dom";
const Posts = ({ match }) => {
return (
<div>
<h2>Topics</h2>
<ul>
<li>
<Link to={`${match.url}/rendering`}>Rendering with React</Link>
</li>
<li>
<Link to={`${match.url}/components`}>Components</Link>
</li>
<li>
<Link to={`${match.url}/props-v-state`}>Props v. State</Link>
</li>
</ul>
<div>
<Route path={`${match.path}/:topicId`} component={Post} />
<Route
exact
path={match.path}
render={() => <h3>Please select a topic.</h3>}
/>
</div>
</div>
)}
export default Posts;
Post Component (Child (Singular) Component)
import React from "react";
const Post = ({ match }) => (
<div>
<h1>Child component</h1>
<h3>{match.params.topicId}</h3>
</div>
);
export default Post;
Not sure what config is lacking here, the parent component is rendering fine on the route while the child component content is not rendering
No error in console.
Parent Routing Configuration
import React from "react";
import { Switch, Route,NavLink } from "react-router-dom";
import Home from "./container/home/Home";
import About from "./container/about/About";
import Posts from "./container/post/posts";
import PageNotFound from "./container/Error/404";
const routes = () => (
<Switch>
<Route path="/" exact component={Home}></Route>
<Route path="/about" component={About}></Route>
<Route exact path="/post" component={Posts}></Route>
<Route component={PageNotFound}> </Route>*/}
</Switch>
)
export default routes;
App.js
import React, { Component } from 'react';
import './App.css';
import Layout from "./hoc/layout/layout";
class App extends Component {
render() {
return (
<Layout></Layout>
);
}}
export default App;
So the mistake in your code is pretty trivial. In the parent Route, i.e the Route that is rendering Posts component, you have an exact keyword and hence Routes like /posts/:postId won't match this exact Route with path /post and hence the inner Routes or nested Child Routes won't work
You need to change your Routes config like
const routes = () => (
<Switch>
<Route path="/" exact component={Home}></Route>
<Route path="/about" component={About}></Route>
<Route path="/post" component={Posts}></Route>
<Route component={PageNotFound}> </Route>*/}
</Switch>
)
export default routes;

Categories

Resources