How to put background image React? - css

I need your help. I am trying to set background image for my header. Photo is in the "public" folder. I prescribe the way to my photo in css. But i have a mistake. What i am doing wrong? How to set the background image in React?
Css
.header{
width: 100%;
height: 550px;
background-image: url(./public/one.jpg);
}
Js
import React from "react";
export let Header = () => {
return <header className='header'>
</header>
}

seems like you're in the src folder, so you'll need to go to the parent directory in order to get to the public folder, like this: "../public/one.jpg" instead of "./public/one.jpg".
I would recommend to add an asset folder within src, instead of using the public folder.

Related

NextJS: Modify third-party component CSS in different pages

With third-party components, the way to include their styles is by importing their stylesheet into _app.tsx or importing the stylesheet into your component that uses the third-party component, as described here: https://nextjs.org/docs/basic-features/built-in-css-support#import-styles-from-node_modules or by adding to next.config.js like so:
// next.config.js
const withTM = require("next-transpile-modules")([
"#fullcalendar/common",
"#fullcalendar/daygrid",
"#fullcalendar/timegrid",
"#fullcalendar/interaction",
"#fullcalendar/react",
"#fullcalendar/list",
To modify the third-party stylesheet, you need to create your own stylesheet and add it to _app.tsx; those modifications might look like this:
// styles/modified-fullcalendar.scss
.fc-col-header {
width: 100% !important;
}
Another option, at least for my use case (Full Calendar) is to use CSS variables as described here in technique 2 on this page: https://fullcalendar.io/docs/css-customization. There was a lengthy thread about this on the Full Calendar issues page, as seen here: https://github.com/fullcalendar/fullcalendar/issues/5393
The problem with all of these methods of customization is that they're global, and so anywhere you use this third-party component it'll look the same. However, in my case, I want to use the component on two different pages, with different styling modifications. With most frameworks, I would simply import the relevant modified stylesheet wherever I needed it, but NextJS doesn't allow that. How can I achieve the modifications I want?
The solution is to wrap the component in a div with a specific class name, then do the css overrides in a nested format for each use case in the override file.
Explanation:
Say your third-party component is FullCalendar. It's being imported and used in the files Foo.tsx and Bar.tsx. In Foo, let's say you want the calendar cells to be green.
To make the modification, you create the file modified-fc.scss and do the following:
// modified-fc.scss
.fc-cell {
background: green !important;
}
You then import modified-fc.scss into _app.tsx in order to apply the styles globally, and you're done. However, this prevents you from changing the cell color to orange in Bar. To circumvent this, just wrap the component:
// Foo.tsx
<div className=".wrapper1">
<FullCalendar/>
</div>
// Bar.tsx
<div className=".wrapper2">
<FullCalendar/>
</div>
and then nest the classes:
// modified-fc.scss
.wrapper1 {
.fc-cell {
background: green !important;
}
}
.wrapper2 {
.fc-cell {
background: orange !important;
}
}
OR
.wrapper1 > .fc-cell {
background: green !important;
}
.wrapper2 > .fc-cell {
background: orange !important;
}

I want to apply a background image to the body of only one component

I am very new to React, so apologies for the mistakes in advance.
In my React app, say I have 2 components and as the CSS styles are global, it picks up CSS styles from all the files.
However, I wish to add a full background image to one of the components which I was able to achieve by using this code in my CSS file:
body {
background-image: url("../image.jpg");
background-position: center;
background-repeat: no-repeat;
background-size: cover;
}
The problem is that the same image is also being applied to another component. I read a few answers and found that I can use ComponentDidMount hook and add the image to the body tag there. I tried that, but it doesn't show anything.
componentDidMount() {
document.body.style.backgroundImage = "url('../image.jpg')";
document.body.style.backgroundPosition = "center";
document.body.style.backgroundRepeat = "no-repeat";
document.body.style.backgroundSize = "cover";
}
EDIT
I realized I had the wrong wording for the question. What I mean to say is that I have two pages in React. For one of the pages, I want a full background image. However, because CSS styles are global, the background image is getting applied to all the pages.
You can use inline styling or specific styling by assigning a specific class or ID to the top element of one component.
INLINE STYLING Example:
// If Background variable has url to the background image.
const style = {
backgroundImage: `url(${Background})`
}
// in component use that inline style
return (
<div style={style}></div>
);
IF YOU WANT TO WORK with body only...
then add a class to body on component A mount and remove the class on component B mount. And attach the background property to the class.
A component usually return some jsx and in most cases a div. In other to apply a css to a single component I mean the jsx the component is rendering. you should define a css class, that apply a background image to the div the component is rendering and make the height of the div the window height. you can do this via inline css all
const MainDiv =()=>(
<div classname="testClass">
This will show background image in the covering the entire body
//Other content of your page can be added here like the rest of your page contents
<header>
This is my blog post
</header>
<nav>
this is my navbar
</nav>
</div>
);
ReactDOM.render(<MainDiv />, document.getElementById("root"));
.testClass{
backgroundImage :"url('../image.jpg')";
backgroundPosition :"center";
backgroundRepeat : "no-repeat";
background-size : "cover";
width: 100%;
height: 100vh
}

Background Image won't show in React component

I'm creating a simple React app (using create react app as a starting point) in which the App.js returns the following:
return (
<div className="App">
<NavBar />
<Main />
</div>
);
}
export default App;
I'm attempting to add an image to Main with the following:
return (
<div className="bg">
<LogInSignUpModal />
</div>
);
}
export default Main;
In the file Main.css I have the following:
/* The image used */
background-image: url("../../images/WorkoutRack.jpg");
/* Full height */
height: 100%;
width: 100%;
/* Center and scale the image nicely */
background-position: center;
background-repeat: no-repeat;
background-size: cover;
}
Unfortunately the image won't appear in the main component (the main component is supposed to take up the entire page below the NavBar. I've tried many different solutions found in other StackOverflow responses but none have worked. What am I missing here?
Hi we can load the image in couple ways in react components itself
import react from 'react'
import imageName from './location/of/image'
class App extends react.Component{
render(){
return(
<img src={imageName} alt="imagename"/>
}
}
2nd way is to using require
All code are similar but instead of importing, require it
import react from 'react'
Const imageName = require ('./location/of/image')
class App extends react.Component{
render(){
return(
<img src={imageName} alt="imagename"/>
}
}
First check this answer:
React won't load local images
If that was not fault, check your parent style or use px for with and height.
Images included in css files are going to taken from the public folder, not the src one.
So make your url relative to where the files are stored within the public folder, including the css in the public file too should make it even easier.
If someone has doubts about this, I'll gladly reply to you in the comments.

Applying CSS stylesheet only to active component

I'm working on a ReactJS app that has a header at the top, a menu on the left, and the "frame" in the middle is where routes and their corresponding components are loaded. I want to be able to apply a CSS stylesheet to specific components only when they are loaded. I also don't want them applied all the time or to the top header or left menu.
My expectation was that adding import 'custom.css'; to a specific component would only apply the stylesheet's styles to that component and it's children when the route is active. Instead, it applies it to the entire page even when the route/component are not loaded.
I understand that an alternative approach is styled components, but, for my use-case, a design company is supplying a stylesheet (which should remain unchanged) that we need to consume only for the sub-module I'm working on and I don't want its styles to affect the rest of the app.
How can I have a stylesheet only applied to my active route/component?
Use simple CSS technique. Suppose you have two components with different css files (say about.css and contact.css). Now consider your both CSS file have one common class with different style properties, like:
about.css
.container{
max-width: 400px;
}
contact.css
.container{
max-width: 500px;
}
Yes in ReactJS both the CSS files will load at the same time and will override any one of the style. so to solve this problem add class to differentiate this styles, like:
about.css
.about-component.container{
max-width: 400px;
}
contact.css
.contact-component.container{
max-width: 500px;
}
If you want apply only when the component is mounted, you can use the lifecycle.
The follow example is based in the idea you are using sass, React, sass-node and have the loaders into webpack.
<pre>
import React from 'react';
import './styles.scss';
class MyComponent {
constructor(props) {
super(props);
this.state = { className: '' }
}
componentDidMount() {
this.setState({
className: 'myOwnClass'
});
}
render(){
return (
<div className={this.state.className}>This is a example</div>
);
}
}
export default myComponent;
</pre>
To be able to only call that specific CSS when you need it you can use CSS Modules. You may need to update your version of react.
When saving your CSS file save it with a ".module.css" eg. "styles.module.css". The CSS in these files can only be used and accessed by hte components where are they are imported. As stated in a tutorial from W3Schools.
Let's say this is your CSS code in styles.module.css:
.container {
color: white;
}
.cont-child {
background-color: red;
}
Then in your JS file you can import the CSS file like this if the JS and CSS files are in the same directory. Make sure you point to the correct path.
import styles from './styles.module.css'
Then in your HTML section you can use it like this:
class Home extends React.Component {
render() {
return(
<main className={ styles.container } >
<div className={ styles["cont-child"]} >
Some div text about something...
</div>
</main>
);
}
}
I currently use both ways to access the selectors, since the styles variable acts like an object. I placed both of them here because the second option is capable of fetching selectors named like "btn-active". Which comes in handy in some situations. Camelcasing is considered cleaner though.
Please note: I originally posted this answer as a reply to a similar question here React CSS - how to apply CSS to specific pages only
I want to be able to apply a CSS stylesheet to specific components
only when they are loaded.
Why not apply the styles inline via React.js?
Step 1. Create the style object for the component:
var componentOneStyle = {
color: 'white',
backgroundColor: 'red'
};
Step 2. Populate the component's style attribute with the style object:
ReactDOM.render(<div style={componentOneStyle}>This is Component One</div>, mountNode);

I cannot use folder path in css in my react app

I cannot set img background in css at all in my react app. but if I style and set img from react component then it works fine, can someone help me out
this will work
const style={
width:'300px',
height:'200px',
backgroundImage: 'url(pictures/backgroundPics/1.jpg)'
}
const Test =()=>(
<div style={style}/>
)
but this won't
import './test.css'
const Test =()=>(
<div className='test'/>
)
css
.test{
background-color: gray;
width: 300px;
height: 200px;
background-image: url(../../public/pictures/randomPics/1.jpg)
}
i have tried to set my css path to many ways I can think of including setting it relative to css file or html file but it either gives me module not found or parse error. my Test component path is src/test/test.js and my css file is in the same test folder. I am using css-loader v0.28.4
It will work if I set web address as the url
background-image: url(http://www.pvhc.net/img226/gzypyldoqaxjhvtyyhei.png)
There's no need to relativity reference the public directory in your CSS. Have you tried:
background-image: url(/pictures/randomPics/1.jpg)

Resources