I have a problem to pass the backgroundImage this is my code:
Home.js
import React from 'react';
import './Home.css';
import AlarmCardInvertida from '../components/AlarmCardInvertida';
function Home() {
const alarmCardInvertidaData = [
{
background: '../../images/banners/casa01.jpg',
},
];
return (
<>
<h2 className='alarm-cards-title'>Funcionalidades de Nuestros Sistemas</h2>
<section className='alarm-cards-section'>
{alarmCardInvertidaData.map((card, index) => (
<AlarmCardInvertida
key={index}
background={card.background}
/>
))}
</section>
</>
);
}
export default Home;
And this is my AlarmCardInvertida.js
import React from 'react'
import './AlarmCardInvertida.css'
function AlarmCardInvertida(props) {
const cardStyle = {
backgroundImage: `url(${props.background})`,
position: 'relative',
zIndex: -3,
width: '100%',
};
return (
<div className='alarm-card-inverted'>
<div style={cardStyle}></div>
</div>
)
}
export default AlarmCardInvertida;
The problem is when render:
<div style="background-image: url("../../images/banners/casa01.jpg"); position: relative; z-index: -3; width: 100%;"></div>
Expected:
<div style="background-image: url('../../images/banners/casa01.jpg'); position: relative; z-index: -3; width: 100%;"></div>
i Try this too:
function AlarmCardInvertida(props) {
const backgroundImageUrl = props.background;
return (
<div className='alarm-card-inverted'>
<div
style={{
backgroundImage: `url(${backgroundImageUrl})`,
backgroundSize: 'cover',
backgroundPosition: 'center',
width: '100%',
height: '300px',
}}
></div>
and others and render ever … background-image: url("
Basically the problem I have is that it doesn’t render the image inside the backgroundImage (if I send for example to use in a <img src=xxxx tag, this works correctly…) The problem is only with the backgroundImage
2
Answers
Your approach seems to be correct to pass the background to the props.
The image may not be showing up since the div containing it is empty. You could try after adding content to it or set a
min-height
value to the div.I have created a working example here with your code.
https://stackblitz.com/edit/stackblitz-starters-2qxpar
All I have changed is that I have added the
minHeight
andbackgroundSize
to the AlarmCardInvertida.js within the card style as below and I can see the image load up just fine.Here’s my solution