React.JS React-Router-Dom applying css on every routes - reactjs

i'm a beginner in react.js and i recently discovered react-router-dom but i have an issue with it if i apply css to my file all the other routes have this css how could i fix that issue?
My Code:
https://i.imgur.com/9imDEdU.png
https://i.imgur.com/GMLk6Q1.png
I guess it's because it import this page on every page but i have no idea how to fix the problem

You can import the css file inside your react component.
For example, you can import the login.css file in your Login component
Edit:
If you want to load the css files on demand, refer
http://www.javascriptkit.com/javatutors/loadjavascriptcss.shtml

The problem occurs because of react bundle all things together.
You may need to set different className for your every page root parent div.
Also, Another way is to set a different CSS/SCS file in the corresponding view Component.
Like if I consider Login.jsx cmponent it return method would be like that:-
For Login.jsx:-
return(
<div className="login-container">
</div>
)
For Registration.jsx:-
return(
<div className="registration-container">
</div>
)

Related

Other component styles are getting applied to the component which I have not imported

Hello I am working on simple crud application in react js 18.0.0. My problem is I have my own styles for one component say eg..Home. But the styles which I have used for other components is also getting applied to Home component even though I did not imported it. Can anyone explain why?
I have attached an image for your reference.
In the above image I was in home component. But if you see the styles the container class in forgetPassword.css and login.css is also getting applied in home component. but In home component I did not imported those two css files(forgetPassword.css and login.css)
Yes this is because by default react does not support css or styles.
you can either use css modules(https://create-react-app.dev/docs/adding-a-css-modules-stylesheet/)
Or
Use styled components.
I suggest you to try the css modules as that will be beginner friendly and easy.
You need to move your css to seperate file and name it [filename].module.css
In your case Home.module.css
Then in your Home.js component import it like import styles from './Home.module.css'
Then in your component use it like
<div className={styles.container} > ... </div>
I also recommend you not to modify the original bootstrap classes, instead create your custom class and add the overrides there.
eg:
<div className={`${styles.container} ${styles.home-container}`} > ... </div>

Using custom images in components react

I have a react component that is used many times on a products page. Each of the components has its own image. Is there a way to dynamically import an image? For example something like
function productPage({imgPath}){
import img from imgPath
return <img src={img}/>
}
and when I use the component I can do something like
<productPage imgPath="/pathToImage">
I have only come across answers that use require (<img src={require("/pathToImage")} />) However, this method does not work for me. Images only load when I use import. I am not sure why this is (maybe using create-react-app only allows for import?)

Is it possible to hydrate (or something else) single component?

My case: I have a page preloader, but it makes using react and it's to long (first paint). SSR could solve this problem, but it's too difficult (I mean solving this problem by full SSR).
I want to use something like React.hydrate but for one single component.
I have <MyCustomPreloader /> component which renders <div class="loader" />, but it render with a long delay (after loading the page).
My idea: For example, inside index.html I can make <div class="loader" /> which will be visible at first paint. Main problem say <MyCustomPreloader /> that I have already rendered div and he must use it without creating new.
I could find the necessary DOM inside the component and work with it, but this means abandoning React and continue to work directly with the DOM component.
I tried to manually add <div class="loader" /> into <div id="root"></div> and use React.hydrate instead of React.render and it works! But React.hydrate tries to hydrate every components before and after loader and this solution is kludge.
I believe that there is a function that can partially hydrate a single component (say to component "use this DOM" instead of making same new element), but I cannot find it.
For example:
const loader = ReactDOM.someMagicFunction(<MyCustomPreloader />, document.getElementById("loader"))
Example of this kludge: https://codesandbox.io/s/hopeful-meadow-qgz6j Description: I have "pre-rendered" loader in index.html, and react after loooong loading gets it and USED it (this DOM element).
Can I hydrate single component with some DOM element?

How to import a component or file in React using variables?

I'm building a web app using React that shows the blueprint for the building you select, in an already selected campus.
I have a "Content" component that loads the campus or building map, depending what you chose.
The "BuildingMap" component needs to load a specific blueprint according to what building you selected. It gets the props.building with the name of the building but I don't know how to load a component using that variable.
I have tried import, fetch and require but nothing seems to work.
Please help.
My code looks something like this:
//Content Component
<BuildingMap building={selectedBuilding} campus={selectedCampus} />
//BuildingMap Component
import *MyBlueprint* from (specific folder depending on the campus selected)
class BuildingMap extends React.Component {
render(){
return (
<div className="blueprint" id={this.props.building}>
{*MyBlueprint*}
</div>
)
}
}
Unfortunately, you cannot import/require components dynamically in React environment.
Depending on how many buildings/blueprints there are, it's possible to import them one by one, create component-building map and pick component by building ID.
If there are many/infinite components to load, I would surely pick another method - don't know content of your problem.
import BlueprintA from './BlueprintA'
import BlueprintB from './BlueprintB'
import BlueprintC from './BlueprintC'
// ...
class BuildingMap extends React.Component {
render(){
const C = {
buildingA: BlueprintA,
buildingB: BlueprintB,
buildingC: BlueprintC,
// ...
}[this.props.building]
return (
<div className="blueprint" id={this.props.building}>
<C />
</div>
)
}
}
This question is pretty old but as I was looking for how to solve the same problem let me give my answer. It can be done with dynamic import React.lazy:
const OtherComponent = React.lazy(() => import('./OtherComponent'));
See more details here: https://reactjs.org/docs/code-splitting.html#reactlazy
To add to #Andreyco's answer:
Using a lookup table of string IDs/names to component classes is a typical React idiom. One common use case is a modal manager component that can render multiple different types of modals. For some examples, see Dan Abramov's answer at "How can I render a modal dialog in Redux?" (not Redux-specific), as well as some of the related articles in the React Component Patterns#Modal Dialogs and Redux Techniques#UI sections of my React/Redux links list.
Per #azium's comment: it is definitely possible to use dynamic importing (via require.ensure() or the new import() function) to load chunks at runtime, and you could add the exports from those dynamically imported chunks into a lookup table when they are loaded.

React render component containing only function

I'm very very new to react (still learning). One thing I noticed is that component always have a return with HTML (jsx) as content.
But I was wondering if it's possible to create a component containing only functions. For example, in my footer I only have static content. Just plain text and a button to go to the homepage. So this is what I'm trying to do:
index.html
<body>
<main id="app"></main>
<footer id="footer">
<!-- Some other content -->
<button onClick={this.onButton}>Home</button>
</footer>
<script src="/app/bundle.js"></script>
</body>
Footer.js
class Footer extends React.Component {
onButton() {
console.log('Button clicked');
}
render() {
console.log('render');
return null;
}
}
render(<Footer/>, window.document.getElementById("footer"));
This way, the component gets executed and I can see the log, however, the button defined in the index.html is removed.
On the other hand, if I remove the render() from the component, I get this error:
Footer(...): No render method found on the returned component instance: you may have forgotten to define render.
One thing I forgot to mention before, and also based on the item 2 of #aks answer, about using plaing html to create the links is that it's going to reload the whole page if I don't use the React router I'm currently using.
So, for example, If I create a link on the fotter with plain html like this:
Contact
When clicking on the link everything else is going to reset, because the page is going to refresh.
This is why it would be better to just use a function from a component instead of using the whole html declared inside the component.
Nice question. I will answer your question in points:
Render method is a required method, you cannot do without it, it can return null, as you are already doing.
If you say that your footer is static markup and links to some part, You don't even need the js file. It is not required.
In case you have components for most other parts, the static content may look too verbose. You can put those content in the render method of the Footer component as make the index.html very clean. Then in case you need more features in future, you can add them safely.
I hope that helps!

Resources