Reputation: 5200
I've been looking at some different options for a method of sharing/importing values from a React component to a Sass/CSS file. I have the background
property of a component being set after receiving props that contain a path to an image (from an API). This is set as an inline style.
I also want to add an opaque layer to the component image on hover. This is easily accomplished with regular CSS, however I can't simply overwrite the background
property to a gradient or color when hovered over.
I need to also fetch the image path being used in the component's inline style in order to apply the opacity over the image.
Component:
render() {
const styles = {
background: `url('...somepath.jpeg') no-repeat center`
}
const item = { ...type, ...this.props.metadata };
return (
<section className="card"
onClick={this.props.cb.bind(null, item)}
style={styles}>
</section>
);
}
Styles:
.card:hover {
cursor: pointer;
background: linear-gradient(rgba(20,20,20, .5), rgba(20,20,20, .5)) !important;
// without the path to build the url, this just deletes the image
}
Basically the style I'm looking to apply on hover would appear like this:
linear-gradient(rgba(20,20,20, .5), rgba(20,20,20, .5)), url('...somepath.jpeg') no-repeat center
Is there an efficient method to accomplish something like this? I could only think of adding mouseover/mouseout event listeners to the component to add "hover" inline styles... but I want to stay way from using inline too much.
Upvotes: 1
Views: 95
Reputation: 6507
This is a perfect use case for styled-components. With styled components you can pass down a url as a prop, while still being able to use the full power of CSS.
Sample code specific to your case:
const Section = styled.section`
&:hover {
cursor: pointer;
${(props) => `background: url(${props.url}) no-repeat center` }
}
`
render() {
const item = { ...type, ...this.props.metadata };
return (
<Secion className="card"
onClick={this.props.cb.bind(null, item)}
url="...somepath.jpeg"
/>
);
}
Upvotes: 1