skip to Main Content

Does anyone know why using react and tailwind. I might be having issues update the background colour state.
Im using a simple colour picker component.
Im collecting hex codes and its supposed to change the background colour when a new colour is selected. I get logs of everything with the correct data. But the update doesnt work and the background turns white.

I have gone through a few attempts to fix this which is why im now using the smallest part of the hex code and cutting off the hashtag to see what changes it would make.
Im using an online thing called SketchPicker. It seems to work great. Im getting all the event data i could ask for.

import React, { useState } from 'react';
import { SketchPicker } from 'react-color';

function TestPage() {
 const [backgroundColour, setBackgroundColour] = useState(`0099FF`)

 const handleChange = (event) => {
  console.log('event', event.hex);
  let str = event.hex
  let newStr = str.slice(1); // "ello World!";
  console.log('newStr', newStr);
  setBackgroundColour(`${newStr}`)
 }

  console.log('backgroundColour', backgroundColour)
  return (
   <div className={`grid relative bg-[#${backgroundColour}] h-[100vh] w-full`}>
    <SketchPicker
     color={backgroundColour}
     onChange={handleChange}
    />
   </div>
  );
  }

  export default TestPage;

my logs
backgroundColour 0968c7 TestPage.jsx:15

  event #2b3d4e TestPage.jsx:8
  newStr 2b3d4e TestPage.jsx:11
  backgroundColour 2b3d4e TestPage.jsx:15

  event #156fc3 TestPage.jsx:8
  newStr 156fc3 TestPage.jsx:11
  backgroundColour 156fc3

2

Answers


  1. I think that tailwind cannot manage colors in that way and you have to send them in the style parameters.

    I know that there is some color that you can send such as bg-gray-100 but not with hex.

    You can do something like this.

    <div className={`grid relative h-[100vh] w-full`} style={{ backgroundColor: `#${backgroundColour}`}}>
        <SketchPicker
         color={backgroundColour}
         onChange={handleChange}
        />
       </div>
    

    Hope it helps you!

    Login or Signup to reply.
  2. you can customize tailwind.config.js file.

    theme: {
        extend: {
          colors: {
            colorname: "#E7F6FD"
          },
          
        },
      },
    

    then use like this
    bg-colorname

    also, you can use hex code directly without adding the color name in config file.
    just add this code in config file.

    mode: "jit",
    purge: {
       content: [
          "./src/**/*.{js,jsx,ts,tsx}",
          "./src/views/*.{js,jsx,ts,tsx}",
          "./src/components/**/*.{js,jsx,ts,tsx}",
        ],
    },
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search