Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In React, how to pass a dynamic variable to a const CSS Style list?

I'm using react-dropzone to allow a user to upload a profile photo.

I define the custom CSS like so:

const dropzoneStyle = {
  width: `200px`,
  height: `200px`,
  backgroundColor: `#1DA1F2`,
};

Inside the method to render the DropZone input, I can detect if their is a file preview which is populated after a user selects an image to be uploaded..

What I want to do is, if the file.preview exists, send the file.preview the the dropzoneStyle so a background-image is added to the CSS.

const renderDropzoneInput = (field) => {
  const files = field.input.value;
  let dropzoneRef;

  if (files[0]) {
    console.log(files[0].preview)
  }

  return (
    <div>
      <Dropzone
        name={field.name}
        ref={(node) => { dropzoneRef = node; }}
        accept="image/jpeg, image/png"
        style={dropzoneStyle}
      >

How can I pass files[0].preview to the style dropzoneStyle with React?

like image 271
AnApprentice Avatar asked Jun 26 '17 01:06

AnApprentice


People also ask

Can I use CSS variables in React?

There are two reasons to switch to CSS variables in your React app: The ergonomics are nice. It unlocks new possibilities! You can do things with CSS variables that are not possible with JS.


1 Answers

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>
);
like image 139
Joe Dalton Avatar answered Nov 13 '22 04:11

Joe Dalton