HTML not showing up on React webpage [duplicate] - javascript

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/>}>

Related

Why react is not rendering anything using router?

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

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 />}>

How to use :params in React router

Having issues with the react-router picking up on a nested route. A param is passed to accommodate for any subsequent links to be conditionally rendered later in the child component passed into Route
import React from "react";
import { Route } from "react-router-dom";
import CollectionsOverview from "../../components/collections-overview/collections-overview";
import CollectionPage from "../collection/collection";
const ShopPage = ({ match }) => {
return (
<div className="shop-page">
<Route exact path={`${match.path}`} component={CollectionsOverview} />
<Route path={`${match.path}/:collectionId`} component={CollectionPage} />
</div>
);
};
export default ShopPage;
import React from "react";
import "./collection.styles.scss";
const CollectionPage = ({ match }) => {
return (
<div className="collection-page">
<h2>COLLECTION PAGE: {match.params.collectionId}</h2>
</div>
);
};
export default CollectionPage;
Route 2 never renders its component on route manipulation
You can use useParams. Please check this example:
import React from "react";
import {BrowserRouter as Router,Switch,Route,Link,useParams} from "react-router-dom";
export default function ParamsExample() {
return (
<Router>
<div>
<h2>Accounts</h2>
<ul>
<li>
<Link to="/netflix">Netflix</Link>
</li>
<li>
<Link to="/zillow-group">Zillow Group</Link>
</li>
<li>
<Link to="/yahoo">Yahoo</Link>
</li>
<li>
<Link to="/modus-create">Modus Create</Link>
</li>
</ul>
<Switch>
<Route path="/:id" children={<Child />} />
</Switch>
</div>
</Router>
);
}
function Child() {
let { id } = useParams();
return (
<div>
<h3>ID: {id}</h3>
</div>
);
}
Source

Creating a button to a new route reactJS

Really struggling with understanding how to create a button which routes to a new page (search.js).
I've tried different methods which some have worked in routing to the link but the page does not change (but I can see the url being changed to the search page).
*sorry at this point the code has been butchered with numerous attempts of adding the button
App.js -
```
import React, { useState } from "react";
import { BrowserRouter as Router, Link } from 'react-router-dom';
import Route from 'react-router-dom/Route';
function App() {
const [joke, setJoke] = useState()
const newJoke = () => {
fetch("http://api.icndb.com/jokes/random")
.then(result => result.json())
.then(result2 => {
console.log(result2)
setJoke(result2.value.joke)
})
return newJoke
}
return (
<Router>
<div className="jokeSection">
<h1>Chuck norris jokes</h1>
<h3>{joke}</h3>
<button onClick={() => newJoke()}>Click here for a chuckle</button>
<button onClick={() => { this.props.history.push("/search"); }}>Search!!</button>
</div>
<ul>
<li>
<Link to="/App">Home</Link>
</li>
<li>
<Link to="/search">Search</Link>
</li>
</ul>
</Router>
)
}
export default App;```
Search.js
import React from "react";
function Search() {
return (
<div>
<h2>Search</h2>
</div>
);
}
export default Search;
Ideally I want a button (just like the button onClick) to route to a new page - search.js.
I'm new to ReactJS and have tried to watch many tutorials but i'm having difficulty.
In your app.js file you need to have <Route> as children of <Router> not <Link>.
You can look over this code:
<Router>
<div>
<Route exact path="/">
<Home />
</Route>
<Route path="/news">
<NewsFeed />
</Route>
</div>
</Router>
The above code will create routes for your react application. Then you can navigate to each of them using <Link> in your Navbar rather than ordinary a tag.

Why isn't my react-router working? URL changes on click but no display on DOM

I have multiple components I am trying to route but I will only show a few components here so I don't overwhelm you. I have installed and imported everything correctly I think.
Here is App.js that controls all the routes, the component "Hello" is for testing, there are no props involved or anything and its still not showing in the DOM. Does it have anything to do with not passing props because before using the router to separate my components, I would just do for example: Are these not being automatically passed with router? I am a beginner using React so any help would be great, thank you!
import React, { Component } from 'react'
import Clients from './components/Clients'
import Lessons from './components/Lessons'
import AddClient from './components/AddClient'
import NavBar from './components/NavBar'
import Hello from './components/Hello'
import AddLesson from './components/AddLesson'
import CalculateIncome from './components/CalculateIncome'
import {Switch, BrowserRouter, Route} from 'react-router-dom'
class App extends Component {
state = {
clients : [],
lessons : [],
}
deleteClient = (id) => {
let clients = this.state.clients.filter(client => {
return client.id !== id
})
this.setState({
clients: clients
})
}
addClient = (newClient) => {
newClient.id = Math.random();
let clients = [...this.state.clients, newClient];
clients.sort((a, b) => a.name.localeCompare(b.name))
this.setState({
clients: clients,
})
}
addLesson = (newLesson) => {
newLesson.id = Math.random();
newLesson.date = Date();
let lessons = [...this.state.lessons, newLesson];
this.setState({
lessons: lessons,
})
console.log(this.state.lessons)
}
render() {
return (
<BrowserRouter>
<div className="App">
<NavBar/>
<Switch>
<Route exact path='/' Component={AddLesson}/>
<CalculateIncome lessons={this.state.lessons} clients={this.state.clients}/>
<Route path='/addClient' Component={AddClient}/>
<Route path='/clients' Component={Clients}/>
<Route path='/lessons' Component={Lessons}/>
<Route path='/hello' Component={Hello}/>
</Switch>
</div>
</BrowserRouter>
);
}
}
export default App;
Here is my navbar.js
import React from 'react'
import {NavLink, withRouter} from 'react-router-dom'
const NavBar = (props) => {
return (
<nav>
<div>
<h1 className="header text-center my-5" >Welcome to the Tennis App</h1>
<div className="container text-center">
<NavLink className="mx-5" exact to="/">Add Lesson</NavLink>
<NavLink className="mx-5" to='/addClient'>Add a New Client</NavLink>
<NavLink className="mx-5" to="/clients">Clients</NavLink>
<NavLink className="mx-5" to="/lessons">Lessons</NavLink>
<NavLink className="mx-5" to="/hello">Hello</NavLink>
</div>
</div>
</nav>
)
}
export default withRouter(NavBar)
And here is hello.js that is just a dummy test component
import React from 'react'
const Hello = () => {
return(
<div className="text-center">Hello there</div>
)
}
export default Hello
I realized I have to use the render={Home} instead of Component={Home}
Here is a link to the answer I found after extensive 2 day research...
https://medium.com/alturasoluciones/how-to-pass-props-to-routes-components-29f5443eee94

Categories

Resources