I have this fully functional and very basic code:
import React from "react";
import ReactDOM from "react-dom";
import {BrowserRouter, Route, Switch} from "react-router-dom";
import Home from "./App/home.jsx";
import About from "./App/about.jsx";
ReactDOM.render(
<BrowserRouter>
<Switch>
<Route exact path="/" component={Home}></Route>
<Route path="/About" component={About}></Route>
</Switch>
</BrowserRouter>,
document.getElementById("main")
);
I realise that no matter what, Home and About components is always going to be loaded, but not always used.
How can I fix this? I've tried:
import React from "react";
import ReactDOM from "react-dom";
import {BrowserRouter, Route, Switch} from "react-router-dom";
import Home from "./App/home.jsx";
import About from "./App/about.jsx";
let path = require("path");
function C(file) {
return function(obj) {
let url = path.join("./App", file);
let C = require(url);
return <C {...obj}/>
}
}
ReactDOM.render(
<BrowserRouter>
<Switch>
<Route exact path="/" component={C("home.jsx")}></Route>
<Route exact path="/" component={C("about.jsx")}></Route>
</Switch>
</BrowserRouter>,
document.getElementById("main")
);
But then, it doesn't get rendered.
So is there any way that I can load only the components I need for the current web page.
perhaps using code splitting in this fashion
https://reactjs.org/docs/code-splitting.html
import React, { Suspense } from 'react';
const OtherComponent = React.lazy(() => import('./OtherComponent'));
const AnotherComponent = React.lazy(() => import('./AnotherComponent'));
function MyComponent() {
return (
<div>
<Suspense fallback={<div>Loading...</div>}>
<section>
<OtherComponent />
<AnotherComponent />
</section>
</Suspense>
</div>
);
}
So perhaps your code could be like this
I have this fully functional and very basic code:
import React from "react";
import ReactDOM from "react-dom";
import {BrowserRouter, Route, Switch} from "react-router-dom";
const Home= React.lazy(() => import('./App/home.jsx'));
const About= React.lazy(() => import('./App/about.jsx'));
ReactDOM.render(
<BrowserRouter>
<Switch>
<Route exact path="/" component={Home}></Route>
<Route path="/About" component={About}></Route>
</Switch>
</BrowserRouter>,
document.getElementById("main")
);
You can use React-Loadable package for the use-case you mentioned above. Example code is shown below, follow along with it.
import Loadable from 'react-loadable';
const loading = () => (
<div>
Loading... //Custom loader
</div>
);
const AsyncLogin = Loadable({
loader: () => import('./Login/index.jsx'),
loading: loading,
});
ReactDOM.render(
<BrowserRouter>
<Switch>
<Route path='/login' component={AsyncLogin} />
</Switch>
</BrowserRouter>,
document.getElementById("main"));
You can find the react-loadable documentation here. Or alternatively, you can configure Webpack and achieve the required results.
Related
When I try using the useLoaderData hook from react-router-dom, it has been giving me the same error
Uncaught Error: useLoaderData must be used within a data router. See
https://reactrouter.com/routers/picking-a-router.
no matter what change I make in the Home Component, so that made me guess the issue is not from there.
This is what my Main.jsx looks like:
import React from 'react'
import ReactDOM from 'react-dom/client'
import { BrowserRouter } from 'react-router-dom'
import App from './App'
import './index.css'
ReactDOM.createRoot(document.getElementById('root')).render(
<React.StrictMode>
<BrowserRouter>
<App />
</BrowserRouter>
</React.StrictMode>
)
My App.jsx:
import React from 'react'
import { Route, Routes } from 'react-router-dom'
import Home, { homeLoader } from './pages/Home'
import About from './pages/About'
import GlobalLayout from './GlobalLayout'
const App = () => {
return (
<>
<Routes>
<Route path='/' element={<GlobalLayout />}>
<Route index element={<Home />} loader={homeLoader} />
<Route path='/about' element={<About />} />
</Route>
</Routes>
</>
)
}
export default App
I think everything in my Home.jsx is fine
I have tried checking out the documentation attached to the error and its not helping.
In order to use the RRDv6.4 Data APIs a data router must be used. See Picking a Router.
Use the createBrowserRouter utility to create a Data router. The created router object is passed to the RouterProvider component. Any routes and components that you want or need to use the Data APIs necessarily need to be declared here at build time as part of the data router creation.
App.jsx
import React from 'react';
import {
createBrowserRouter,
createRoutesFromElements,
RouterProvider,
Route,
Routes
} from 'react-router-dom';
import Home, { homeLoader } from './pages/Home';
import About from './pages/About';
import GlobalLayout from './GlobalLayout';
const router = createBrowserRouter(
createRoutesFromElements(
<Route element={<GlobalLayout />}>
<Route path="/" element={<Home />} loader={homeLoader} />
<Route path="/about" element={<About />} />
</Route>
)
);
const App = () => {
return <RouterProvider router={router} />;
};
export default App;
Main.jsx
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import './index.css';
ReactDOM.createRoot(document.getElementById('root')).render(
<React.StrictMode>
<App />
</React.StrictMode>
);
createBrowserRouter
RouterProvider
createRoutesFromElements
I am learning basic crud operations in React, and ran into this problem. In the components, I am primarily expecting to see one word in each page. But when I am starting the react app, pages appear to be blank. I guess I missed something about react-router or react-router-dom. Codes are given here.
index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
reportWebVitals();
App.js
import React from "react";
import ReactDOM from "react-dom/client";
import {
BrowserRouter,
Routes,
Route
} from "react-router-dom";
import books from "./components/books.jsx";
import add from "./components/add.jsx";
import update from "./components/update.jsx";
function App() {
return (
<div className="App">
<BrowserRouter>
<Routes>
<Route path="/" element= {<books />} />
<Route path="/add" element= {<add />} />
<Route path="/update" element= {<update />} />
</Routes>
</BrowserRouter>
</div>
);
}
export default App;
books.jsx
import React from "react";
const books = () => {
return (
<div>books</div>
)
}
export default books;
add.jsx
import React from "react";
const add = () => {
return (
<div>add</div>
)
}
export default add;
update.jsx
import React from "react";
const update = () => {
return (
<div>Update</div>
)
}
export default update;
Sub-directories and files in client directory
enter image description here
Codes may seem incomplete as I have encountered this problem at the halfway. I tried some fixes from youtube and google, but could not right it.
React components are Capitalized. From JSX in Depth:
User-Defined Components Must Be Capitalized
When an element type starts with a lowercase letter, it refers to a
built-in component like <div> or <span> and results in a string
'div' or 'span' passed to React.createElement. Types that start
with a capital letter like <Foo /> compile to
React.createElement(Foo) and correspond to a component defined or
imported in your JavaScript file.
By using <book /> React assumes this is an HTML element and doesn't create a React element from your component code.
import React from "react";
const Books = () => {
return (
<div>books</div>
)
}
export default Books;
import Books from "./components/books.jsx";
import Add from "./components/add.jsx";
import Update from "./components/update.jsx";
function App() {
return (
<div className="App">
<BrowserRouter>
<Routes>
<Route path="/" element={<Books />} />
<Route path="/add" element={<Add />} />
<Route path="/update" element={<Update />} />
</Routes>
</BrowserRouter>
</div>
);
}
I am doing a personal React.js project. I am trying to use react-router-dom, but I haven't been able to make it work. I did the BrowserRouter in the App.js. Till there the app works fine, but I cannot make the routing redirect dynamically to a map item. I tried to follow the documentation and some tutorials unsuccesfully. The data comes from the Star Wars API This is the code:
App.js:
import './App.css';
import { Route, BrowserRouter as Router, Routes } from "react-router-dom";
import Home from './components/Home';
import MovieDetail from './components/MovieDetail'
import Navbar from './components/Navbar';
function App() {
return (
<Router>
<>
<Navbar />
<Routes>
<Route exact path='/' element={<Home />} />
</Routes>
<Routes>
<Route exact path to='/:movieId' element={<MovieDetail />} />
</Routes>
</>
</Router>
);
}
export default App;
ItemDetail:
import { useEffect, useState } from "react";
import { useParams } from "react-router-dom";
const MovieDetail = () => {
const { movieId } = useParams();
const [result, setResult] = useState([]);
const fetchData = async () => {
const res = await fetch("https://www.swapi.tech/api/films/");
const json = await res.json();
setResult(json.result);
}
useEffect(() => {
fetchData();
}, []);
let movieMatch = (result.find(value) => value.properties.title == movieId)
return (
<div>
<h2>
{result
.find((value) => {value.properties.title == movieId})}
</h2>
</div>
);
}
export default MovieDetail;
UPDATE
This is a link to the whole code in codesand with updated App.js
From your code I'm assuming you're using React Router v6 in your project. Try the below code:
import './App.css';
import { BrowserRouter, Routes, Route } from "react-router-dom";
import Home from './components/Home';
import MovieDetail from './components/MovieDetail'
import Navbar from './components/Navbar';
function App() {
return (
<BrowserRouter>
<Routes>
<Navbar />
<Route path='/' element={<Home />} />
<Route path=':movieId' element={<MovieDetail />} />
</Routes>
</BrowserRouter>
);
}
export default App;
Checkout React Router's Documentation for more detail.
if you are using index.js as a wrapper for app.js <BrowserRouter /> or <Router /> in your case is not used in app.js it's used in index.js otherwise it will not work
index.js should look like this : -
import React from "react";
import ReactDOM from "react-dom";
import { BrowserRouter } from "react-router-dom";
function App() {
return <h1>Hello React Router</h1>;
}
ReactDOM.render(
<BrowserRouter>
<App />
</BrowserRouter>,
document.getElementById("root")
);
**For example just Let's say you are having "/movies" route and you want when ever your app (route = "/") starts / loads up to be redirected to "/movies" **
then wrap the routing logic with *<Switch />* ,make use of Redirect property of router dom to redirect from "/" to "/movies" and use component instead of element to render the corresponding component plus dont wrap with <Routes> </Routes> every time you are doing the route as we used it in index.js
then app.js will be : -
import './App.css';
import { Route, BrowserRouter as Router, Routes } from "react-router-dom";
import Home from './components/Home';
import MovieDetail from './components/MovieDetail'
import Navbar from './components/Navbar';
function App() {
return (
<>
<Navbar />
<Switch>
<Route exact path='/movies' component={<Home />} />
<Route exact path to='movies/:movieId' component={<MovieDetail />}
// to redirect from "/" to "/movies"
<Redirect from="/" to="/students"></Redirect>
);
}
I have problem with router-dom. I am working according to youtube tutorial, I cannot resolve below error:
[landingPageLayout] is not a component. All component children of must be a or <React.Fragment>. I would be greateful for some guidance.
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import { BrowserRouter } from 'react-router-dom';
import App from './App';
import reportWebVitals from './reportWebVitals';
ReactDOM.render(
<React.StrictMode>
<BrowserRouter>
<App />
</BrowserRouter>
</React.StrictMode>,
document.getElementById('root')
);
App.js
import './App.css';
import { Routes, Route } from 'react-router-dom';
import landingPageLayout from './components/layouts/landingPageLayout';
import homePage from './components/pages/homePage';
const App = () => {
return (
<Routes>
<landingPageLayout>
<Route path="/">
<homePage/>
</Route>
</landingPageLayout>
</Routes>
);
}
landingPageLayout.js
import React from 'react';
import Header from '../navigation/header';
const landingPageLayout = ({...otherProps}) => {
return (
<div>
<Header/>
</div>
)
}
export default landingPageLayout;
As Nicholas said in comments, your react components should always be capitalized.
Other than that, Routes component only accepts or <React.Fragment> as children so you can't add your layout like that. What you can do is something like this:
const App = () => {
return (
<Routes>
<Route
path='/*'
element={
<LandingPageLayout>
<HomePage />
</LandingPageLayout>
}
/>
</Routes>
);
}
If you have several routes that need this layout, you should replace HomePage with another component that has all the routes. For example we can call it PrivateRoutes. Then in code above you replace <HomePage /> with <PrivateRoutes /> and then your PrivateRoutes component should look like this:
const PrivateRoutes = () => {
return (
<Routes>
<Route path="home" element={<HomePage />} />
<Route path="page1" element={<Page1 /> />
//rest of routes
</Routes>
);
}
I'm having issues with my project, actually i'm trying to handle a 404 page when the user enters different url outside of the Routes in my App, but using my knowledge of React and react-router only needs to put the last route has no path and exact path wrapped by a Switch from react-router but not work well, the home page is rendering the Home and the NotFound components at same time.
I've tried to remove Container component inside the Router but that makes that all of the components after MenuBar disappears.
I've tried to put path='*' in the last Route having 2 components rendered in the same page.
A picture of what i'm talking about:
2 components at same time
My project have 3 principal files:
1.- Index.js :
import ReactDOM from 'react-dom';
import * as serviceWorker from './serviceWorker';
import ApolloProvider from './ApolloProvider';
import 'semantic-ui-css/semantic.min.css';
import 'animate.css/animate.min.css';
import './App.css';
ReactDOM.render(ApolloProvider, document.getElementById('root'));
serviceWorker.unregister();
2.- ApolloProvider.js (using Apollo with GraphQL) :
import React from 'react';
import App from './App';
import ApolloClient from 'apollo-client';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { createHttpLink } from 'apollo-link-http';
import { ApolloProvider } from '#apollo/react-hooks';
const httpLink = createHttpLink({
uri: 'http://localhost:5000/graphql'
});
const client = new ApolloClient({
link: httpLink,
cache: new InMemoryCache()
});
export default (
<ApolloProvider client={client}>
<App />
</ApolloProvider>
);
3.- And finally App.js :
import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import { Container } from 'semantic-ui-react';
import MenuBar from './Components/MenuBar';
import Home from './Pages/Home';
import Login from './Pages/Login';
import Register from './Pages/Register';
import NotFound from './Pages/404';
const App = props => (
<Router>
<Switch>
<Container>
<MenuBar />
<Route exact path='/' component={Home} />
<Route exact path='/login' component={Login} />
<Route exact path='/register' component={Register} />
<Route path='*' component={NotFound} />
</Container>
</Switch>
</Router>
);
export default App;
I only need to render Home component when the user visits '/' but it's weird how react-router is rendering two components at same time, please le me know if you find where i'm wrong or a solution for that, i'll being posting updates if i find a solution or whatever.
Thanks in advance mates!.
Thanks to #skyboyer and #Hugo Dozois the issue was fixed, this is the updated App.js for future references:
const App = props => (
<Router>
<Container>
<MenuBar />
<Switch>
<Route exact path='/' component={Home} />
<Route exact path='/login' component={Login} />
<Route exact path='/register' component={Register} />
<Route path='*' component={NotFound} />
</Switch>
</Container>
</Router>
);
Best Regards!