Hello
I’m using frontity with a headless wordpress.
My question is how can i get the featured image url of my post to use it as a background-img on the in-js-css ?
Maybe some of you have the answer i need ?
Tanks you
Hello
I’m using frontity with a headless wordpress.
My question is how can i get the featured image url of my post to use it as a background-img on the in-js-css ?
Maybe some of you have the answer i need ?
Tanks you
I don’t 100% know if this is best practice, but I did it with something like this, for a slider I built.
const SliderItem = ({ state, item, active }) => {
const media = state.source.attachment[item.featured_media];
let media_url = "";
if(media !== undefined) {
if("source_url" in media) {
media_url = media.source_url;
}
}
return (
<SliderItemContainer className={active} style={{backgroundImage: "url(" + media_url + ")"}}>
</SliderItemContainer>
);
return null;
};
Good luck!
Thanks a lot !
It’s works,
// >> Fetch data of the article to display it on homepage as a recent article
const recentTag = state.source.post[138];
console.log(recentTag);
// >> Fetch the featured media URL by ID
const featuredMediaId = recentTag.featured_media;
const media = state.source.attachment[featuredMediaId].source_url;
console.log(media);
// Display a background-image style
const backgroundImageStyle = {
backgroundImage: "url(" + media + ")"
};
// >> Fetch the author object by the article ID
const author = state.source.author[recentTag.author];
console.log(author);
// >> Fecth the categories items by the article ID
const category = state.source.category[recentTag.categories];
console.log(category);
return (
<Link link={recentTag.link} >
<Recent__card style={backgroundImageStyle}>
<div className="article__recent-title">
<h3>Dernier sujet digital</h3>
</div>
<div className="article__title">
<div className="article__title-info">
<p>{author.name}</p>
<div className="category-style"><h4>{category.name}</h4></div>
</div>
<h2>{recentTag.title.rendered}</h2>
</div>
</Recent__card>
</Link>
)
}
export default connect(recent);
Nice!
Nice work guys!
Just remember to use the css
prop from "frontity"
instead of React’s style
: https://docs.frontity.org/learning-frontity/styles#reacts-style-prop
Ah awesome, thanks! Here is an updated example for anyone else looking:
const SliderItem = ({ state, item, active }) => {
const media = state.source.attachment[item.featured_media];
let media_url = "";
if(media !== undefined) {
if("source_url" in media) {
media_url = media.source_url;
}
}
return (
<SliderItemContainer css={css`background-image: url(${media_url});`}>
</SliderItemContainer>
);
return null;
};