I'm trying to make a little React App and it is the first time I'm using Router.
import { render } from "react-dom";
import {
BrowserRouter,
Routes,
Route
} from "react-router-dom";
import App from "./App";
import Shop from './routes/shop';
import style1 from "./App.css";
import style2 from "./shop.css";
const rootElement = document.getElementById("root");
render(
<BrowserRouter>
<div style={style1}><Routes>
<Route path="/" element={<App/>} />
</Routes></div>
<div style={style2}><Routes>
<Route path="shop" element={<Shop />}/>
</Routes></div>
</BrowserRouter>,
rootElement
);
It works great and I can use http://localhost:3000/ and http://localhost:3000/shop, but it is not switching the css files.
both CSS files get loaded on both pages
I know that React is a One Page Application, but please tell me how to remove the frickin App.css from http://localhost:3000/shop
So I want App.css on http://localhost:3000/ and Shop.css on http://localhost:3000/shop
I would be very grateful for every answer!
I don't why you're stating the CSS styles while browsing Routes.
Just import your CSS files in your component.js
Like In your case,
import { render } from "react-dom";
import {
BrowserRouter,
Routes,
Route
} from "react-router-dom";
import App from "./App";
import Shop from './routes/shop';
const rootElement = document.getElementById("root");
render(
<BrowserRouter>
<Routes>
<Route path="/" element={<App/>} />
</Routes>
<Routes>
<Route path="shop" element={<Shop />}/>
</Routes>
</BrowserRouter>,
rootElement
);
This is your components,
import "./App.css";
import React from 'react';
export default function App(){
//YOUR CODE HERE
}
Another Shop Component
import "./shop.css";
import React from 'react';
export default function Shop(){
//YOUR CODE HERE
}
This'll work Fine!
To add onto what Shivam said, what's happening with your code currently is that React is importing both CSS files and applying them.
This is because the syntax you're using is incorrect. You can't import a css file as something else:
import styles1 from "./App.css"
is actually just importing App.css and applying it to App.js and Shop.js.
You can do what Shivam said, however, if you want to style your react app in the way you were trying to, you can use css modules.
These work in the way that you were trying to use a css file - you can import them and use inline styling. I wouldn't recommend this approach however, since you would have to style every JSX expression in 'App.js' in this way. Just setting 'style={style}' only passes a prop to App.js with that style component, it doesn't actually apply it.
Check out this link. It covers css modules and some other ways of styling css in react. Best!