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})`
..
Related
I am working on a react project, where I want to conditionally render a div above an existing div that currently covers the screen with an image. I would like the existing div to reduce in height, by shrinking the size of the image, when the second div conditionally renders. The second div can have a varied height. ( e.g. list of items).
This is simplified version of what I have in my App so far:
function App() {
const [show, setShow] = useState(false);
return (
<div
style={{
border: "solid",
width: "100%",
maxHeight: "100vh"
}}
>
{show && (
<div>
<div style={{ height: "300px", backgroundColor: "red" }}></div>
<button
onClick={() => {
setShow(false);
}}
>
Close
</button>
</div>
)}
<div
style={{
display: "flex",
justifyContent: "center"
}}
>
<img
src="https://i.imgur.com/LiAUjYw.png"
alt="test"
style={{
maxWidth: "100%",
height: "auto"
}}
/>
</div>
<button onClick={() => setShow(true)}>SHow</button>
</div>
);
}
It initially looks like this: https://imgur.com/a/R0e74Xk
And on clicking the 'Show' button, it looks like this: https://imgur.com/a/Iy6osio
As you can see the bottom div gets shifted down, and goes over the container div.
I was wondering how I can make the div responsive enough to change its height when the other element is rendered.
I am fairly new to styling so any help on this would be greatly appreciated.
Thank you.
Here's one simple idea. See how the style is given to the divs like so:
<div
style={{
display: "flex",
justifyContent: "center"
}}
>
Note how the style has this weird {{ }} notation. That's because style accepts an object, and the object here is:
{
display: "flex",
justifyContent: "center"
}
You could take that object and save it as a variable somewhere, for example:
const styleWhenShow = {
display: "flex",
justifyContent: "center",
height: "100px"
}
const styleWhenNoShow = {
display: "flex",
justifyContent: "center",
height: "500px"
}
Since you already have your show state, now it's just a matter of replacing the style prop with:
style={show ? styleWhenShow : styleWhenNoShow}
In case you don't want to repeat some common styles between the show and noshow styles, you can also do something like:
const commonStyle = {
display: "flex",
justifyContent: "center"
}
const styleWhenShow = {
height: "100px"
}
const styleWhenNoShow = {
height: "500px"
}
And set the style prop like:
style={show ? { ...commonStyle, ...styleWhenShow } : { ...commonStyle, ...styleWhenNoShow }}
Im trying to set a static image to be laid out on full height and width of page but it doesn't seem to work, any suggestions ?
Image and code below.
import Image from './image.jpg'
var containerStyle = {
width: "100%",
height: "400px",
backgroundImage: `url(${Image})`,
backgroundPosition: 'center',
backgroundSize: 'cover',
backgroundRepeat: 'no-repeat'
};
export default function Navbar() {
return (
<div>
<img style={containerStyle} />
</div>
);
}
var containerStyle = {
width: "100vw",
height: "100vh",
...
};
I'm having an issue getting an image to appear within my React project. I've done it before and actually copied the same exact code to put it into my project, but for some reason nothing is showing up. I looked in the console and inspected the image and it's showing that there is something there, but just not rendering somehow. Nothing I search for online has a similar issue so I'm wondering if I'm just missing something, and that's what causing it not to render.
Here is the parts of my file that pertains to my question.
import React from 'react';
import { Link } from 'react-router-dom';
import Button from '../../components/Spinner/Button';
import ATABanner from '../../../public/Images/ATAbanner-flip.png';
import ATADouble from '../../../public/Images/ATAdouble-1.png';
import ATASingle from '../../../public/Images/ATAsingle-1.png';
import '../../StyleSheets/AdContract.css';
import '../../StyleSheets/Button.css';
export default class CustomerPage extends React.Component{
constructor(props){
super(props);
this.state = {
QuoteID: this.props.match.params.id,
CustomerFirst: "",
CustomerLast: "",
CurrStep: 1,
StoreList: [],
StoresSelected: [],
AdSize: "",
AdSelected: "",
}
}
... extra stuff and methods here
AdSizeHandler(e){
console.log(e.target.id);
switch(e.target.id){
case "SINGLE": this.setState({AdSize: e.target.id});
break;
case "DOUBLE": this.setState({AdSize: e.target.id});
break;
case "BANNER": this.setState({AdSize: e.target.id});
break;
}
}
RenderAdSelected(){
let img = null;
let ad = this.state.AdSize;
if(ad == "SINGLE"){
img = (
<img id="ad-image-single" name='ADSingle' src={ATASingle} alt="" width="100%" scrolling="no"/>
)
}else if(ad == "DOUBLE"){
img = (
<img id="ad-image-double" name='ADDouble' src={ATADouble} alt="" width="100%" scrolling="no"/>
)
}else if(ad == "BANNER"){
img = (
<img id="ad-image-banner" name='ADBanner' src={ATABanner} alt="" width="100%" scrolling="no"/>
)
}
return img;
}
render(){
return(
<div id="CustomerContainer" style={{width: '100%', height: '100%'}}>
<div id="CustomerContent" className="fade-in" style={{textAlign: 'center', width: '100%', height: '100%', overflowY: 'auto'}}>
<div id="Welcome" style={{marginTop: '5%'}}>
<p style={{fontSize: '35px', fontWeight: 'bold'}}>Hello, {this.state.CustomerFirst + " " + this.state.CustomerLast}</p>
<p style={{fontSize: '20px', color: 'orange'}}><b>Your Quote Is Almost Ready!</b></p>
</div>
<div style={{marginTop: '5%', color: '#0F9D58', fontSize: '37px'}}>
<p><b>Step: {this.state.CurrStep}</b></p>
</div>
<div id="InnerContainer" style={{width: '80%', marginLeft: 'auto', marginRight: 'auto'}}>
{this.RenderStoreSelect(this.state.CurrStep)}
<div id="ad-select">
<div className="fade-in" id="ad-prompt">
<p style={{fontSize: '20px'}}><b>Please Select Your Ad Size</b></p>
</div>
<div id="ad-buttons" style={{display: 'inline-block', marginTop: '2%'}}>
<span style={{display: 'flex'}}>
<Button name="SINGLE" color="G-green" click={this.AdSizeHandler.bind(this)}></Button>
<Button name="DOUBLE" color="G-green" click={this.AdSizeHandler.bind(this)}></Button>
<Button name="BANNER" color="G-green" click={this.AdSizeHandler.bind(this)}></Button>
</span>
</div>
<div>
<img id="adImage" name='ADSingle' src={ATASingle} alt="" width="100" height="100"/>
</div>
</div>
</div>
{this.ConfirmQuote()}
</div>
</div>
)
}
}
Here is proof that it's retrieving the image:
If anyone has any idea what I'm possibly doing wrong, please let me know. Thanks.
I found out the reason for this issue. The problem is that I am in a different route than the home route '/'. I solved my problem by doing this instead: <img id="adImage" name='ADSingle' src={`/${ATASingle}`} alt="" width="100" height="100"/>
I am using https://www.npmjs.com/package/react-multi-carousel in one of my react project and I have implemented it and it works fine.
I am now in the need to implement the text (legend) over the carousel exactly like https://codesandbox.io/s/lp602ljjj7 which uses another package but I need that scenario and not that package because my need is different (Using nextjs so multi-carousel supports ssr and hence using it).
My only need is need to know how to implement the legend text over the carousel image using react-multi-carousel.
My code example: https://codesandbox.io/s/react-multi-carousel-playground-bt3v7
Change the structure of the return statement to the following structure.
Then you can store the value of the legend in the image array and pass the value to the p tag
const Simple = ({ deviceType }) => {
return (
<Carousel
ssr
partialVisbile
deviceType={deviceType}
itemClass="image-item"
responsive={responsive}
>
{images.slice(0, 5).map((image, index) => {
return (
<div key={index} style={{ position: "relative" }}>
<img
draggable={false}
alt="text"
style={{ width: "100%", height: "100%" }}
src={image}
/>
<p
style={{
position: "absolute",
left: "50%",
bottom: 0,
color: "white",
transform: " translateX(-50%)"
}}
>
Legend:{index}.
</p>
</div>
);
})}
</Carousel>
);
};
export default Simple;
Live demo
You should change array structure like below.
const images = [
{
image: "https://images.unsplash.com/photo-1549989476-69a92fa57c36?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60",
text: "First image",
}
];
Then inside loop just add text and style it our way!
const Simple = ({ deviceType }) => {
return (
<Carousel
ssr
partialVisbile
deviceType={deviceType}
itemClass="image-item"
responsive={responsive}
>
{images.map(image => {
return (
<div>
<img
draggable={false}
alt="text"
style={{ width: "100%", height: "100%" }}
src={image.image}
/>
{/* Have to style so this should see over the image */}
<span>{image.text}</span>
</div>
);
})}
</Carousel>
);
};
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!