I am working on a GatsbyJS project, using Contentful, and have created a template 'BlogPost'. Inside this template, I have imported a 'ResearchSlider' component. However, the images are not displaying at all.
I have passed down the image url data, as props, down to the researchSlider, which is then put inside the component state, and used in a function that passes each piece of image data into the 'Slide' child component, using a for loop. In 'Slide', the piece of image data is used as the value for backgroundImage in the styles of a div.
I would like to understand why they are not displaying and how I can fix this.
Here is the relevant code.
ResearchSlider component:
export default class ResearchSlider extends React.Component {
constructor(props) {
super(props);
this.state = {
images: [this.props.firstSlide,
this.props.secondSlide,
this.props.thirdSlide
],
translateValue: 0,
index: 0
}
this.renderSlides = this.renderSlides.bind(this);
this.handleClickPrevious = this.handleClickPrevious.bind(this);
this.handleClickNext = this.handleClickNext.bind(this);
this.slideWidth = this.slideWidth.bind(this);
}
renderSlides() {
const images = this.state.images;
let slides = []
for(let i = 0; i < images.length; i++)
slides.push(<Slide key={i} image={images[i]} />)
return slides
}
render() {
const { translateValue } = this.state
return(
<div className='slider'>
<div className="slider-wrapper"
style={{
transform: `translateX(${translateValue}px)`,
transition: 'transform ease-out 0.3s'
}}>
{ this.renderSlides() }
</div>
<ClickPrevious slideRight={this.handleClickPrevious}/>
<ClickNext slideLeft={this.handleClickNext}/>
</div>
);
}
'Slide' component:
import React from 'react';
const Slide = ({image}) => {
const styles = {
backgroundImage: `url("${image}")`,
backgroundSize: 'cover',
backgroundRepeat: 'no-repeat',
backgroundPosition: '50% 60%'
}
return <div className="slide" style={styles}></div>
}
export default Slide
Here is a screenshot of the inspection:
contentful assets URLs don't have the protocol attached to them they will in the following format //images.contentful.com/......
when setting this url to the src
of an <img>
tag the browser will assign the protocol automatically based on the protocol you app is using. But using the url in css you need to append explicitly the protocol to the url.
You Slide component should look like this.
const Slide = ({image}) => {
const styles = {
backgroundImage: `url("https:${image}")`,
backgroundSize: 'cover',
backgroundRepeat: 'no-repeat',
backgroundPosition: '50% 60%'
}
return <div className="slide" style={styles}></div>
}
export default Slide