How to add background image from local folder to a container - javascript

I want to set the background image of a container div from an image from a local folder. Does anyone know what i need to add to my code/ how to edit it to do this? Currently the image isnt showing for some reason.
class Team extends React.Component{
render(){
let style = {
backgroundRepeat: 'no-repeat',
backgroundImage:'url("../images/Football_Field.png")',
backgroundSize: '100% 100%',
backgroundPosition: 'center',
width: '100%',
height: '100%',
border: '2px dashed #333'
}
return (
<div className="container" style={style}>
<i className="fas fa-tshirt"></i>
</div>
)
}
}
export default Team
The image is in a 'image' folder inside the src folder. (/src/images/Football_Field.png)
The Team components file path is '/src/components/Team'.
Would anyone also know how to do this if i instead used a ui container class?

You could do something like it in your render method :)
Do Know that the path is rooted at the public folder once it's compiled
render()
{
const image = './images/tasse_kandinsky.webp';
return(
<div className='product'>
<div className='product-image' style={{backgroundImage: 'url('+image+')'}}>
</div>
</div>
)
}

Depending on your webpack configuration, you could do something like this:
import backgroundImage from "../images/Football_Field.png";
class Team extends React.Component{
render(){
let style = {
backgroundRepeat: 'no-repeat',
backgroundImage:'url(' + backgroundImage + ')',
backgroundSize: '100% 100%',
backgroundPosition: 'center',
width: '100%',
height: '100%',
border: '2px dashed #333'
}
return (
<div className="container" style={style}>
<i className="fas fa-tshirt"></i>
</div>
)
}
}
export default Team
Otherwise add your image to your public folder and change the url accordingly.

Maybe this helps ->
https://create-react-app.dev/docs/using-the-public-folder/
All you need is a static folder to serve assets, and if you used create-react-app, you just need to put your images in the public folder and follow the doc above.

Related

problem with loading local image in react js

I'm having trouble showing an image using div in react js. the path is correct because I can display it using an img tag.
I can't use the import method because the filename is going to be taken from a database table.
this is my code: (Sandbox)
App.js
import "./styles.css";
import Test from "./components/Test";
export default function App() {
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<Test />
</div>
);
}
./components/Test.js
import img1 from "../assets/images/sandwich.jpg";
const Test = () => {
return (
<div>
<p>This uses the img tag</p>
<img
src={img1}
style={{ width: "100px", height: "100px" }}
alt="an img tag"
/>
<p>And this uses a div with backgroundImage</p>
<div
style={{
backgroundImage: `url("../assets/images/sandwich.jpg")`,
backgroundSize: "cover",
backgroundPosition: "center",
width: "200px",
height: "200px",
border: "1px solid black"
}}
></div>
</div>
);
};
export default Test;
Thank you for giving us a sandbox to test. Was really helpful.
INSTEAD OF WRITING YOUR CODE LIKE THIS:
import img1 from "../assets/images/sandwich.jpg";
const Test = () => {
return (
<div>
<p>This uses the img tag</p>
<img
src={img1}
style={{ width: "100px", height: "100px" }}
alt="an img tag"
/>
<p>And this uses a div with backgroundImage</p>
<div
style={{
backgroundImage: `url("../assets/images/sandwich.jpg")`,
backgroundSize: "cover",
backgroundPosition: "center",
width: "200px",
height: "200px",
border: "1px solid black"
}}
></div>
</div>
);
};
export default Test;
WRITE YOUR CODE LIKE THIS:
import img1 from "../assets/images/sandwich.jpg";
const Test = () => {
return (
<div>
<p>This uses the img tag</p>
<img
src={img1}
style={{ width: "100px", height: "100px" }}
alt="an img tag"
/>
<p>And this uses a div with backgroundImage</p>
<div
style={{
backgroundImage: `url(${img1})`,
backgroundSize: "cover",
backgroundPosition: "center",
width: "200px",
height: "200px",
border: "1px solid black"
}}
></div>
</div>
);
};
export default Test;
The difference is that you don't write your backgroundImage property like this:
backgroundImage: `url("../assets/images/sandwich.jpg")`,
You write it like this:
backgroundImage: `url(${img1})`,
as img1 will contain a react generated link for your image in assets folder you should use img1 as a link in url of the background image as
{
// ...
backgroundImage: `url(${img1})`,
// ...
after watching this video I tried using require like this and it works wonderfully. I hope this can help other people who are stuck with this problem.
const Test = () => {
const img2 = require('../assets/images/sandwich.jpg');
// or if this doesn't work, try adding .default after require
// so it will be require('../assets/images/sandwich.jpg').default
..
<div style={{
backgroundImage:`url(${img2})`
..

How to create an image with color gradient in React's JSX?

This is what I have so far:
homepageImage: {
position: "relative",
textAlign: "center",
height: "100vh",
backgroundImage: `linear-gradient(
#3A8DFF,
#86B9FF
), url("images/bg-img.png")`,
},
<div className={classes.homepageImage}>
I got the above code by referencing this Stackoverflow post, but I guess this method doesn't work with JSX? The colors with the gradient displays in the div, but the image does not appear. I can confirm the url is the correct path as I tested with an <img> tag with "images/bg-img.png" as the src and the image appears.
Would it be a better approach to create a gradient with the <img> tag instead of the <div> tag? Not sure where to go from here.
Try this :
You need to use rgba() to specify the opacity of the color.
App.js
import React from 'react';
import './style.css';
export default function App() {
return (
<div>
<h1>How to create an image with color gradient in React's JSX</h1>
<div style={homepageImage} />
</div>
);
}
const homepageImage = {
position: 'relative',
textAlign: 'center',
height: '100vh',
backgroundSize: 'cover',
backgroundImage: `linear-gradient(
rgba(58, 141, 255, 0.9),
rgba(134, 185, 255, 0.3)
), url("https://images.unsplash.com/photo-1593642532400-2682810df593?ixid=MnwxMjA3fDF8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=750&q=80")`
};
Demo : Stackblitz

Div in React doesn't get the maximum size

Having a React app with this structure:
index.js
...
ReactDOM.render(
<Provider
store=...
>
<BrowserRouter>
<App>
//other components
</App>
</BrowserRouter>
</Provider>,
document.getElementById('root')
);
App.js
export default (props) => {
return (
<div style={{ backgroundColor: 'red' }}>
<div
className='container'
style={{
width: '100vw',
height: '100vh',
paddingBottom: '32px',
paddingLeft: '37px',
paddingRight: '37px',
paddingTop: '20px',
backgroundColor: 'green',
}}
>
{props.children}
</div>
</div>
);
};
container class contains:
.container {
height: 100vh;
width: 1100vw;
}
My question is: why isn't the green as big as the red one? (plus/minus padding, doesn't matter)
I tried width: 100%, 100wh, auto, etc. No one worked. I want that element to be as big as its parent.
This is how it looks: https://imgur.com/a/maFt9CV
I put a black rectangle over the app's data because it's not important in this case.
The property you are looking for is vw not wh. So changing width: '100wh' to width: '100vw' should solve your problem.
Your container class is adding a
max-width: 960px
to your green rectangle
You can either remove the container class or add
maxWidth: '100vw'
to the styles of your green div
The width units you are using are not right: try with vw or vh instead of wh.
You can check it at MDN - CSS values and units
Note: I have test it, after you fix de units, and the App.js works

How to solve TypeError: jquery__WEBPACK_IMPORTED_MODULE_1___default(...)(...).faceDetection is not a function

I am trying to use a face detection library. I have linked it in my index.html with script tag and want to use that file in my profile_pic component. On componentDidMount when I call the function it says that face_detection is not a function. When I used the same file with simple javascript it ran successfully. Now how do I use it with react?
I am getting the image from img tag and there is a file input control that is used to change the value of image dynamically.
This is my render method
render() {
return (
<div
style={{
marginTop: "20px",
display: "flex",
flexDirection: "column",
alignItems: "center"
}}
>
{/* div for upload photo starts*/}
<div>
<input
accept="image/*"
type="file"
id="image_upload"
style={{ display: "none" }}
onChange={e => {
this.handle_image_upload(e);
}}
/>
<label htmlFor="image_upload">
<img
id='picture'
src={this.state.image}
alt="Man or Woman"
style={{ width: "150px", height: "150px", cursor: "pointer" }}
/>
</label>
</div>
</div>
);
}
and here is the componentDidMount lifecycle method
componentDidMount() {
document.getElementById("image_upload").addEventListener("change",()=>{this.face_detection()})
}
This is the face_detection function
face_detection=()=>{
console.log($('#picture'))
$('#picture').faceDetection({
complete: function (faces) {
if (faces.length > 0) {
console.log('There is a face in this image')
}
}
});
}
I have successfully used the same library without react. Now how do I solve this error?
It seems the library that provides 'faceDetection()' function is not defined. Related library should be defined in 'webpack.config.js' or in one of js files of project using 'import' or 'require'. For example, below line imports 'myLibrary' (which locates inside 'libraries' dir) in your React component:
import * as myLibrary from '../libraries/myLibrary';
Now, 'faceDetection()' can be used like this:
myLibrary.faceDetection(...);

Image onError Handling in React

I am trying to grab the maxresdefault of multiple YouTube thumbnails. Some YouTube videos simply don't have a high res thumbnail photo so I want to catch that with an onError prop on an img element. For some reason my function is not triggering when I get the 404 img error. Any ideas? Thanks in advance.
class FeaturedVideo extends Component<Props> {
addDefaultSrc = (e) => {
e.target.src = this.props.background.replace("maxresdefault", "hqdefault")
}
renderVideo = (props) => (
<div
style={{
width: "100%",
height: "100%",
backgroundSize: "contain",
}}
className="featured-community-video"
>
<img onError={this.addDefaultSrc} src={props.background} alt="" />
<div className="featured-community-video-title">
<h2 style={{ fontSize: "0.8em" }}>WATCH</h2>
<h1 style={{ fontSize: props.titleFontSize }}>{props.title}</h1>
</div>
</div>
)
render() {
return (
<div
key={this.props.postId}
style={{
width: this.props.width,
height: "50%",
}}
className="featured-community-video-container"
>
<Link to={routeCodes.POST_DETAILS(this.props.postId)}>
{this.renderVideo(this.props)}
</Link>
</div>
)
}
}
To achieve this, I would suggest rendering the <img /> based on the state of your <FeatureVideo/> component.
You could for instance, create an Image object, attempt to load the background image and by this, reliably determine if the image fails to load. On the images success or failure to load, you would then setState() on your <FeaturedVideo/> component with the appropriate background value which would instead be used to rendering you actual <img/> element:
class FeaturedVideo extends Component<Props> {
componentDidMount() {
if(this.props.background) {
// When component mounts, create an image object and attempt to load background
fetch(this.props.background).then(response => {
if(response.ok) {
// On success, set the background state from background
// prop
this.setState({ background : this.props.background })
} else {
// On failure to load, set the "default" background state
this.setState({ background : this.props.background.replace("maxresdefault", "hqdefault") })
}
});
}
}
// Update the function signature to be class method to make state access eaiser
renderVideo(props) {
return <div
style={{
width: "100%",
height: "100%",
backgroundSize: "contain",
}}
className="featured-community-video">
{/* Update image src to come from state */}
<img src={this.state.background} alt="" />
<div className="featured-community-video-title">
<h2 style={{ fontSize: "0.8em" }}>WATCH</h2>
<h1 style={{ fontSize: props.titleFontSize }}>{props.title}</h1>
</div>
</div>
}
render() {
return (
<div
key={this.props.postId}
style={{
width: this.props.width,
height: "50%",
}}
className="featured-community-video-container"
>
<Link to={routeCodes.POST_DETAILS(this.props.postId)}>
{this.renderVideo(this.props)}
</Link>
</div>
)
}
}
Hope that helps!

Categories