In React, how to pass a dynamic variable to a const CSS Style list?
I usually just define the style as an arrow function that returns the style object, and pass in whatever parameters are needed for the style. There is a shorthand notation for returning an object literal from an arrow function that works nicely for this.
const style = () => ({});
Just remember to only use ternary operators if using the shorthand, otherwise you would just need to explicitly return
an object.
So, for your style:
const dropzoneStyle = (isPreview) => ({
width: `200px`,
height: `200px`,
backgroundColor: `#1DA1F2`,
backgroundImage: (isPreview) ? 'url(/path/to/image.jpg)' : 'none',
});
This adds the image is isPreview
is true, but keeps it blank if not.
Then in your component, call the function where the style goes:
return (
<div>
<Dropzone
{...otherProps}
style={ dropzoneStyle(isPreview) }
>
</div>
);
Assuming files[0].preview
returns a file (image) URL, you should be able to set a new style and pass it to the Dropzone
component.
Something along these lines:
const renderDropzoneInput = (field) => {
const files = field.input.value;
let dropzoneRef;
render() {
let dropzoneStyle = {
width: `200px`,
height: `200px`,
backgroundColor: `#1DA1F2`,
};
if (files[0]) {
dropzoneStyle = {
width: `200px`,
height: `200px`,
backgroundColor: `#1DA1F2`,
backgroundImage: `url(${files[0].preview})`,
// or to use a fixed background image
// backgroundImage: `url(/path/to/static/preview.png)`,
backgroundPosition: `center center`,
backgroundRepeat: `no-repeat`
};
}
return (
<Dropzone
name={field.name}
ref={(node) => { dropzoneRef = node; }}
accept="image/jpeg, image/png"
style={dropzoneStyle}
/>
)
}
}
a spread operator could be used to DRY this code a bit, with:
let dropzoneStyle = {
width: `200px`,
height: `200px`,
backgroundColor: `#1DA1F2`,
};
if (files[0]) {
dropzoneStyle = {
...dropzoneStyle,
backgroundImage: `url(/path/to/static/preview.png)`,
backgroundPosition: `center center`,
backgroundRepeat: `no-repeat`
};
}