Search code examples
javascriptreactjssetstateuse-state

Forcing component re-render with setState not working as expected


I am using react-usa-map package to visualize USA map (https://www.npmjs.com/package/react-usa-map). I created my map component as per package's instructions but I am facing the issue with re-rendering it when state is chosen. Here is my entire component code:

import React, { useState, useEffect } from "react";
import "./map.css";
import USAMap from "react-usa-map";

const PublicGraphMap = () => {

  const [selected, setSelected] = useState();

  const mapHandler = (event) => {
    setSelected(event.target.dataset.name);
  };


  const statesFilling = (state) => {
    console.log(state); // OUTPUTING THE CHOSEN STATE CORRECT
    return {
      state: {
        fill: "navy",
        clickHandler: () => console.log(state),
      },
    };
  };

  return <USAMap customize={statesFilling(selected)} onClick={mapHandler} />;
};

export default PublicGraphMap;

For some reason everything is working and in statesFilling() function selected is displaying in console correctly. But I don't know why returning is not working. Everything in return object is not working and if I put for example NJ instead of state here:

 return {
      NJ: {
        fill: "navy",
        clickHandler: () => console.log(state),
      },
    };
  };

It is coloring NJ state without problem. Here is sandbox example:

https://codesandbox.io/s/pedantic-kowalevski-7rt7d?file=/src/App.js

I want to be able dynamically to choose state and color it.


Solution

  • You need to specify the key as a state code, not the literal "state".

    const statesFilling = (state) => {
      console.log(state);
      return {
        [state]: { // <-- interpolate the state value to be used as key
          fill: "navy",
          clickHandler: () => console.log(state)
        }
      };
    };