Can't load a local background image in ReactJS - javascript

I'm having some problems taking an image from my local machine with my React App.
I'm trying to take image like
style={{ backgroundImage: `url(../../assets/images/games/${img}))` }}
But it's not working, and I don't understand why.
My file is located in
C:\Users\Me\Desktop\myreactapp\src\routes\GameSlider\index.js
And my images are in
C:\Users\Me\Desktop\myreactapp\src\assets\images\games
This is how my index.js looks now (without imports):
const GameSlider = ( { key, id, name, img, minPrice, maxSlots } ) => {
return (
<div key={key}>
<div className="home-games">
<div className="img" style={{ backgroundImage: `url(../../assets/images/games/${img}))` }} alt="..." />
<div className="price">
<IntlMessages id="gameSlider.startingAt" />
<p>
<span className="min">{minPrice}</span>
<span className="per-slot">
<IntlMessages id="gameSlider.perSlot" />
</span>
</p>
</div>
<span className="title">{name}</span>
<div className="features">
<Col span={24} className="feature">
<Icon type="lock" /> <IntlMessages id="gameSlider.upTo" /> {maxSlots} <IntlMessages id="general.slots" />
</Col>
</div>
<Link to={`/order/${id}`}><Button className="comet-buy-button" style={{ background: 'rgb(241,89,89)', borderRadius: '20px' }}>BUY NOW!</Button></Link>
</div>
</div>
);
}
export default GameSlider;

1 - Import your img:
import img from '../../pics/asteroids.jpg'
2 - And then use it:
<div style={{backgroundImage: `url(${img})`}}>Test</div>
On your page this div will look like this:
<div style="background-image: url("/static/media/asteroids.c8ab11b3.jpg");">Test</div>

Absolute path and relative path is always one of the issue for developers to fix :P so there is a another way to solve this easily.
You can use something like this:
import the whatever image in the namespace
import backgroundImg from '../images/BackgroundImage.jpg';
then use it the element like this
<img src={backgroundImg} />
let me know if this works.

If you want to use image or images without importing them, you should put your assets folder into the public folder and use them like below:
src='/assets/images/pic.jpeg'

I tried for hours lots of different solutions and in the end it came down to having quotes inside the url call, like this:
`url('${ImportedImage}')`
Quite weird that this happened though because in previous projects it has always worked fine without the inner quotes (actually, I've noticed in the past that it worked with OR without the quotes). Only thing I've done differently this time is used the TypeScript template of create-react-app to set up the project.

Related

How do I pass props value to inline css in react.js

I want to pass props value to inline css.
Here is my code
function Thread(props) {
return(
<div
class="img"
style={{ backgroundImage: "url(Assets/thread-1.webp)" }}
></div>
)}
I want to replace the value image url using {props.ThreadImageUrl} But I don't know how to write JS inside inline css.
Here is what I want to achieve.
function Thread(props) {
return(
<div
class="img"
style={{ backgroundImage: {props.ThreadImageUrl} }}
></div>
)}
I tried JavaScript string Concatenation but it doesn't work. I'm still newbie to Js and React framework. Glad if someone can help me on this.
You should do:
backgroundImage: `url(${props.ThreadImageUrl})`,

react-responsive-carousel is not displaying properly

I am working on an online ecommerce website using react js. On the details page for every product, I am using react-responsive-carousel to allow the user to slide through all images for that specific product. I also wanted there to be thumbnails underneath that are also selectable. react-responsive-carousel was a perfect choice because it was easy to implement and the look/functionality was almost exactly how I wanted it to look. Initially, everything was working fine, but for some reason the carousel stopped displaying properly. My code involving the carousel is the same as it was before, so I'm not sure what the issue is.
This is how the images are displaying now:
Top view of the carousel
Lower view of the carousel
As you can see, the images are stacked on top of each other, as well as the thumbnails. The next/previous buttons are in the wrong spot and each image is prepended with a bullet point.
This is my code for the entire product details page:
import React, { Component } from 'react';
import {ProductConsumer} from '../context.js';
import {Link} from 'react-router-dom';
import SizeSelector from './SizeSelector.js';
import {Carousel} from 'react-responsive-carousel';
export default class Details extends Component {
render() {
return (
<ProductConsumer>
{value => {
const {id, title, img, info, price, size} = value.detailProduct;
const images = img.map(index =>
<div>
<img className="img-fluid" key={id} src={index} alt="Product"/>
</div>
);
return (
<div className="mx-2 pb-5">
<div className="row">
<div className="col-10 mx-auto text-center my-5">
<h1>{title}</h1>
</div>
</div>
<div className="row">
<div className="col-10 mx-auto col-md-6 mb-3">
<Carousel>{images}</Carousel>
</div>
<div className="col-10 mx-auto col-md-6 mb-3">
<h3 className="mb-2">${price}</h3>
<p className="mb-5">{info}</p>
<SizeSelector />
<Link to="/products">
<button className="btn btn-black mr-5">Back to products</button>
</Link>
<span className="btn btn-black"
onClick={() => {
if (value.size === "")
{
value.openSizePrompt();
}
else
{
value.addToCart(id, value.size);
value.openModal(id, value.size);
}
}}>
Add to cart
</span>
</div>
</div>
</div>
)
}}
</ProductConsumer>
)
}
}
Also, I have a javascript file containing the product data. When a storeProduct is selected, the values of the product are set to a detailProduct. From there, I can get all of the data about that product. 'img' is the object containing the array of images. Each product may have a different amount of images (usually 2-4), so I have to dynamically create the <div> <img/> </div> using the img.map function.
If anyone has a clue on how to fix this issue, I would greatly appreciate the help. I really do not want to go through the effort of implementing my own carousel. I am more than happy to provide other information that may help fix the problem.
I solved the problem with a simple import:
import 'react-responsive-carousel/lib/styles/carousel.min.css'
However, before I ran into this issue, everything was displaying fine without this import. I am not sure what changed that required me to do this.

Conditional Dynamic import of image in javascript for react

the usual way of importing image in react/javascript is as such:
import image from './img/img3.png';
...
<div>
<img src={image} />
</div>
I'm looking to conditionally import an image in javascript in the following manner:
there are several images in the img folder of the format - img1.png, img2.png, img3.png, etc..
I'd like to calculate which image to import inside the javascript file and then subsequently import ONLY that image, something in the lines of:
filename = `./img/img${num}.png`
import(filename);
...
<div>
<img src={filename} />
</div>
any idea how to go about doing this?
I found the answer. for conditional imports of image, do something like this:
<img src={require(`./img/${imageNum}.png`)} alt="Img" className={classes.Img} />

Facebook Create React App Build - Add Image As Prop Type

I have a component comment.js
export default function Comment (props) {
return (
<div className="comment-wrapper">
<img src={props.userImage} />
<p className="comment">{props.commentTitle}</p>
</div>
);
}
So I just simply want to have that component in the parent component as
<Comment userImage="IMAGE_LINK" commentTitle="BLAH BLAH" />
Again, I am using the Create-React-App build system from facebook. With that being said I know I can hard code an image using the following
<img src={require(`./images/MY-IMAGE.png`)} />
The code above works perfectly fine for the test image I am trying to load. However, when needed dynamically for the component the issue gets a bit more complex.
Now with the comment.js component above, I cannot do
<img src={require("./images" + {props.userImage})} />
I have taken a look at one thread on this site as well as reading this blog post on the issue and can still not come to a conclusion.
How can I handle image assets being passed as props to a component, in this case?
you can use import
// parent component
import MenuImage from '/img/menu.png'
<Comment image={MenuImage} commentTitle="Title"} />
then on Comment component
export default props => (
<img src={props.image} alt='' />
)

Inject component into specific div without Redux

There is a "portal" pattern which specifies that an element should be appended to the document.body. I want something similar to this, however, it must append to a specific component. My basic layout component would look as follows (Codepen Here):
<div className={styles.container}>
<div className={styles.header}>
<Navbar />
</div>
{/* Here be the problem */}
<PortalTarget />
<div className={styles.content}>
<div className={styles.leftSidebar}>
<SidebarNav />
</div>
<div className={styles.main}>
{children}
</div>
</div>
</div>
Instead of rendering to document.body, it should find the PortalTarget element (ideally only one would be rendered) and then append the <Portal> into that DOM Node.
I am specifically having trouble creating and storing a reference to the <PortalTarget>, I can't seem to find a good way to do it without redux.
Is there a way to do this in React?
If using an external library issue not a concern, just type "react portal" or "react gateway" on any search engine.
There a few battle-tested libraries out there.

Categories

Resources