Search code examples
reactjsreact-dropzone

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?


Solution

  • 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`
      };
    }