Error encountered when accessing color background in the state of Material UI

My eyes are feeling strained, and I'm working on implementing a slider that can adjust both the radius and color of a button.

This sandbox successfully updates the radius.


  Here is the code:
  
  (Code content)
  

Currently, my focus is on utilizing a color picker to modify the background color of the button, along with the font color eventually.

I've encountered an error message related to `this.state`. Any suggestions?

Here is another sandbox in progress with the error - https://codesandbox.io/s/material-demo-forked-l35qy?file=/demo.js

Below is the code snippet with the error:


  (Code content)

Answer №1

Utilizing state inside of useStyles is not recommended since you only have access to the theme and not any props. It's suggested to use the makeStyles call instead, as it allows you to pass some props. This issue has already been addressed in a previous answer with a helpful example.

Exploring how to pass props to material UI style

Another concern is that the functional component being used does not handle states in the right manner. I have revised the code by implementing the useState hook so that it can correctly handle the color for you.

export default function InputSlider() {
  const classes = useStyles();
  const [value, setValue] = React.useState(30);
  const [color, setColor] = React.useState({ background: "#fff" });

  const handleSliderChange = (event, newValue) => {
    setValue(newValue);
  };
  const handleInputChange = (event) => {
    setValue(event.target.value === "" ? "" : Number(event.target.value));
  };
  const handleBlur = () => {
    if (value < 0) {
      setValue(0);
    } else if (value > 30) {
      setValue(30);
    }
  };
  const handleClick = (color) => {
    setColor(color);
  };

  const handleClose = () => {
    setColor({ displayColorPicker: false });
  };

  const handleChange = (color) => {
    setColor(color);
  };
  return (
    <div className={classes.root}>
      <style>
        {`:root {
          --borderRadius = ${value}px;
        }`}
      </style>
      <Button
        style={{ borderRadius: value }}
        variant="contained"
        color="primary"
        value="value"
        onChange={handleSliderChange}
        className={classes.Button}
      >
        Fire laser
      </Button>
      <Grid container spacing={2}>
        <Grid item xs>
          <Slider
            value={typeof value === "number" ? value : 0}
            onChange={handleSliderChange}
            aria-labelledby="input-slider"
          />
        </Grid>
        <Grid item>
          <Input
            value={value}
            margin="dense"
            onChange={handleInputChange}
            onBlur={handleBlur}
            inputProps={{
              step: 10,
              min: 0,
              max: 24,
              type: "number"
            }}
          />
        </Grid>
      </Grid>
      <div>
        <Button style={useStyles.color}></Button>

        <div style={useStyles.swatch} onClick={handleClick}>
          <div style={useStyles.color} />
        </div>
        {color ? (
          <div style={useStyles.popover}>
            <div style={useStyles.cover} onClick={handleClose} />
            <SketchPicker color={color} onChange={handleChange} />
          </div>
        ) : null}
      </div>
    </div>
  );
}

Answer №2

@RichardHpa is absolutely right, you cannot access state in makeStyles and it seems like you are confusing class component with functional component. In this scenario, it is advisable to use useState() throughout.

You already have an example of how to set the border radius, so you can follow that same pattern to apply it to your background color when styling the Button directly.

Check out the codesandbox here:

https://codesandbox.io/s/material-demo-forked-djh78?file=/demo.js

<Button
    style={{
        borderRadius: value,
        background: `rgba(${color.r}, ${color.g}, ${color.b}, ${color.a})`

        // You might need another color picker for text color. Otherwise, the background color will be the same as the text color.
        // color: `rgba(${color.r}, ${color.g}, ${color.b}, ${color.a})`
    }}
    variant="contained"
    color="primary"
    value="value"
    onChange={handleSliderChange}
    className={classes.Button}
>

No need to thank me, @RichardHpa deserves all the credit.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When a parameter is passed into a React-Query function with an undefined value, it can lead to the API returning a 404 error

Two parameters are sent from the frontend to trigger a GET request in another TypeScript file. It seems that one of the parameters is not successfully passed due to unknown rerenders, resulting in a 404 Error being returned by the API call in the console. ...

How can I position a Button at the center of my Grid item using Material UI?

In my React 16.13.0 application, I am utilizing Material UI's Grid and trying to center the content of a button in the middle of a row. Here is what I have tried: center: { alignItems: "center", width: "100%", }, halfRow: { width: "5 ...

Can you use React Hooks to implement refs for ScrollView within a functional component?

Currently, I am in the process of transitioning a react native project from utilizing all class components to functional components with hooks. One of the challenges I am facing is converting a messaging page that includes a ScrollView functionality for ...

Highlighting text within ReactJS using Rasa NLU entities

Currently, I am working on a React application that retrieves data from the Rasa HTTP API and displays it. My goal is to tag the entities in a sentence. The code functions correctly for single-word entities but encounters issues with two-word entities (onl ...

What is the best way to make the NextJS Image Component in React JSX automatically adjust its height?

I need to maintain the aspect ratio while keeping the width fixed. Can you assist me in automatically adjusting the height? I prefer to stick with using the Nextjs Image component if feasible. const Logo = ({ logo }) => { if (logo) { return ( ...

Create a list using ReactJS

I've been working on rendering a dynamic list in JSX, but I'm facing issues displaying the items. Below is my code snippet where I attempted to use useState const [orderList, setOrderList] = useState([]) and setOrderList(prev => [...prev, chil ...

The error states that the type '() => string | JSX.Element' cannot be assigned to the type 'FC<{}>'

Can someone help me with this error I'm encountering? I am fairly new to typescript, so I assume it has something to do with that. Below is the code snippet in question: Any guidance would be greatly appreciated. const Pizzas: React.FC = () => { ...

I successfully installed the Firebase tools using npm, but encountered an error during the process

Alert: Please choose at least one feature. Press SPACEBAR to select features, or mention a feature by executing firebase init [feature_name] ...

The ThemeProvider does not automatically provide theme injections

After creating a theme using the createTheme method from @mui/material/styles, I attempted to apply this theme using ThemeProvider from the same package. This snippet showcases the dark theme that was created: export const darkTheme = createTheme({ pale ...

An effective solution to address the Eslint warning regarding the prohibition of spreading specific props

Just getting started with React and I have a question. How can I address the Prop spreading is forbidden Eslint warning that keeps popping up? After reading through the Eslint documentation, it seems like I have to destructure all props like this: con ...

Utilize the onClick event to access a method from a parent component in React

Looking for guidance on accessing a parent component's method in React using a child component? While props can achieve this, I'm exploring the option of triggering it with an onClick event, which seems to be causing issues. Here's a simple ...

What is the most effective way to compare a nested array using the map or filter function in order to return only the first match

Here is a code snippet showcasing the data object containing information for the codeworks array with code and text values. There is a key array named code = ["ABC","MDH"] and the expected output is displayed in the following code snippets. const data = ...

Issue retrieving nested object in NextJS

view-component.js const ViewComponent = () => { const route = useRoute(); //All good here const data = fetchData(); console.log(data); //Issue arises with this line const profileData = data.profile; console.log(profileData) ...

After the animation is complete, the TextField will automatically redirect to the main page

Recently, I encountered an issue while trying to implement a stylized input field from @material-ui. The code snippet I used was: <TextField id="outlined-basic" className={classes.inputField} color="primary" label="Messa ...

The ideal login page design

I apologize for my lack of knowledge in React, but I am quite new to it and have been struggling with this issue for days. I am having trouble creating a login page in ReactJS. Here is the code in my app.js: import React from 'react'; import {Ha ...

You are unable to utilize global SCSS in Next.js as the Global CSS is restricted to being imported only from files within your Custom <App> component

After setting up node-sass in my next.js application, I attempted to include my global scss file using import '../styles/style.scss'; in the _app.js component, but encountered an error: The system is alerting that Global CSS cannot be imported fr ...

What is the best way to update the state of a response from an API call for a detailed object using React context, so that there is no need to retrigger the API call

I'm currently developing a react native typescript project. How can I assign the data received from an API call to my context object? I want to avoid making the API call every time the component is loaded. Instead, I want to check if the context alr ...

Remove an array object in React Redux

I recently started using Redux and I’ve encountered a major issue. Whenever I try to remove an object from an array, the map function stops working. Do you have any tips or suggestions? reducer.js: const initialState = { storeState: { name: ...

React Router V6 - page is not found in browsing history

Currently, I am encountering an issue with react router v6. While on the detail page, if I press the arrow in Chrome to go back to the previous page, it takes me to the page before the previous one. I checked the history by long pressing on the back arrow, ...

Determining the precise spacing needed for a personalized cursor

Currently, I'm facing an obstacle in my attempt to design a custom cursor/crosshair inside a canvas. The problem lies in the Length, Width, and Gap dimensions assigned to the four rectangles that make up the cursor, as it is resulting in an incorrect ...