Using inline CSS to apply conditional styles to a component in React is a great way to customize the

I'm currently working on customizing the styles of some buttons depending on their 'active' status and whether the user is hovering over them. So far, it's partially working but I'm encountering behavior that I can't fully comprehend.

How can I implement conditional styling for a component based on its state and user interaction?

For reference, I have set up an example in this SANDBOX

Here is the primary JS file excerpt:

demo.js

import React from "react";
import PropTypes from "prop-types";
//import { makeStyles } from "@material-ui/core/styles";
import { withStyles } from "@material-ui/styles";
import { Button } from "@material-ui/core";

const useStyles = theme => ({
  root: {
    backgroundColor: theme.palette.secondary.paper,
    width: 500
  },
  pageButton: {
    backgroundColor: "black",
    color: "blue",
    width: 30,
    minWidth: 20,
    "&:hover": {
      backgroundColor: "green"
    }
  },
  normalButton: {
    width: 30,
    minWidth: 20,
    backgroundColour: "red"
  }
});

class Feature extends React.Component {
  constructor(props) {
    super(props);
    this.state = { currentPage: 0 };
  }
  handleClick(page) {
    this.setState({ currentPage: page });
  }

  fetchPageNumbers() {
    return [1, 2, 3];
  }
  render() {
    const classes = this.props.classes;
    return (
      <div className={classes.root}>
        {this.fetchPageNumbers().map((page, index) => {
          return (
            <div>
              <Button
                onClick={() => this.handleClick(page)}
                key={page}
                className={
                  this.state.currentPage === page
                    ? classes.pageButton
                    : classes.normalbutton
                }
              >
                {page}
              </Button>

              <Button
                onClick={() => {}}
                key={page * 20}
                className={classes.normalButton}
              >
                {page * 20}
              </Button>
            </div>
          );
        })}
      </div>
    );
  }
}

Feature.propTypes = {
  classes: PropTypes.object.isRequired
};

export default withStyles(useStyles)(Feature);

The issue lies in how the first row of buttons reacts. The second row applies the styles correctly. However, the first row only reflects changes when a button is clicked. What I aim to achieve is setting the state based on whether the current button is active (i.e., state == buttonNumber), and also accounting for user hover interactions across all buttons.

Answer №1

How can I dynamically apply styles to a component based on its state and user behavior?


Implementing conditional styles for user behavior

If you want to apply styles when the component is being hovered over, you can use the following CSS:

"&:hover": {
  // Hover styles
}

Applying conditional styles based on component parameters (props)

Unfortunately, makeStyles does not have direct access to the props passed to a component.


However, there are ways to work around this limitation.

1. Using injectSheet HOC

It's important to note that the useStyles function in your code is not actually a hook.

const styles = props => ({
  root: {
    width: props.size === 'big' ? '100px' : '20px'
  }
})

or

const styles = {
  root: {
    width: props => props.size === 'big' ? '100px' : '20px'
  }
}

Then, use it like this:

const CustomComponent = ({size, classes}) => <Component className={classes.root} />;

export default withStyles(styles)(CustomComponent);

2. Utilizing style hooks with parameters (for functional components)

import { makeStyles } from "@material-ui/core/styles";
const useStyles = makeStyles(theme => ({
  root: {
    width: props => props .size === "big" ? "100px" : "20px"
  }
}));

const classes = useStyles();

Alternatively, you can do:

import { makeStyles } from "@material-ui/core/styles";
const useStyles = params =>
  makeStyles(theme => ({
    root: {
      width: params.size === "big" ? "100px" : "20px"
    }
  }));

const classes = useStyles(whateverParamsYouWant)();

Answer №2

Responding to @keikai, it is also possible to provide an object as an argument to the styles() hook instead of just passing props which was causing an error in my case.

import { makeStyles } from "@material-ui/core/styles";
const useStyles = makeStyles(theme => ({
  root: {
    width: ({ size }) => (size === "big" ? "100px" : "20px")
  }
}));

const classes = useStyles({ size });

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

How to access vue.js 3 single file component functions from within a script tag

Imagine having a single file component structured like this: <template> // content irrelevant </template> <script> export default { data() { return { redLocations: [ "Isfahaan", "Qom", ...

Using jQuery to dynamically format a date with variables

Looking to properly format a date for use in a compare function to sort data $(xml).find("item").each(function () { var dateText = $(this).find("Date").text(); var year = dateText.substr(0,4); var month = dateText.subst ...

Tips for preventing duplicate Java Script code within if statements

In my function, there are various statements to check the visibility of fields: isFieldVisible(node: any, field: DocumentField): boolean { if (field.tag === 'ADDR_KOMU') { let field = this.dfs_look(node.children, 'ADDR_A ...

Utilizing traditional JavaScript variables within Express.js or Node.js: A comprehensive guide

How can I successfully export variables from regular JavaScript to be used in ExpressJS? I attempted to use 'exports' but it didn't yield the desired results. For instance, in a regular JS file: var search = 'hello'; exports = s ...

Interacting with icons using TouchableOpacity and onPress functionality

I am attempting to implement onPress functionality for icons using TouchableOpacity. However, when I click on the icon, nothing happens and there are no console logs displayed. I have also tried enclosing the icon within an additional View, but that appro ...

Trigger keydown and click events to dynamically update images in Internet Explorer 7

There is a next button and an input field where users can enter the page number to jump to a specific page. Each page is represented by an image, like: <img src="http://someurl.com/1_1.emf" > // first page <img src="http://someurl.com/2_1.emf" ...

Generating a container DIV with loops and ng-class in AngularJS

Currently, I am working on developing a dynamic timeline using AngularJS. To populate my timeline, I have successfully configured the data fetching from a JSON file. You can see what I have accomplished so far on PLNKR: http://plnkr.co/edit/avRkVJNJMs4Ig5m ...

Set the variable after catching it

Within my AngularJS application, I am utilizing a $watchCollection function to call the getBalance(address) function within the listener. $scope.$watchCollection('settings', function() { for (i = 0; i < $scope.settings['accounts&ap ...

Is it possible to register multiple service workers within a single scope simultaneously?

My Reactjs app uses a service-worker.js file to make it a PWA. Now, I also want to incorporate push notifications using FCM, which requires adding firebase-messaging-sw.js to the public folder. However, both of these files need to be in the same scope for ...

Searching in sequelize for a specific date using a clause

Operating System: Linux (Lubuntu) Programming Language: Javascript (Node js) Framework: express js Database: mysql "data" represents a Date field from the "activitat" table Upon running this query using Sequelize.js models.TblActivitat.findAll( ...

Obtain information using AJAX calls with jQuery Flot

Having an issue with jQuery Flot that I need help resolving. PHP output (not in JSON format): [[1, 153], [2, 513], [3, 644]] ~~ [[1, 1553], [2, 1903], [3, 2680]] Here is the jQuery call: $.ajax({ url: 'xxx.php', success: function (dat ...

Troubleshooting the issue with the htmlFor attribute

I have encountered an issue with creating radio buttons and labels using JavaScript. Despite adding the 'for' attribute in the label using 'htmlFor', it does not apply to the actual DOM Element. This results in the label not selecting t ...

A step-by-step guide on increasing native Time variables in JavaScript

How can I dynamically and repetitively add time (both hours and minutes) in JavaScript to effectively increment a date object? There are times when I need to add minutes, or hours, or a combination of both - and I want the resulting total time to be return ...

Determining the navigation changes within a React browser

Hi there, I'm using browserHistory.goForward() and browserHistory.goBack() to navigate forward and backward in my app with arrow buttons. However, I need a way to determine if the route has actually changed after executing browserHistory.goForward/goB ...

I am looking to modify the visibility of certain select options contingent upon the value within another input field by utilizing ngIf in AngularJS

I am currently utilizing Angularjs 1.x to develop a form with two select fields. Depending on the option selected in the first select, I aim to dynamically show or hide certain options in the second select field. Below is the code snippet for the form: &l ...

Can the functionality of two-way data binding be achieved in Angular without utilizing ng-model and ng-bind?

During an interview, I was presented with this question which sparked my curiosity. While I have a foundational understanding of AngularJS and its ability to enable two-way data binding using ng-model and ng-bind, I am interested in exploring alternative ...

How to dynamically modify ion-list elements with Ionic on button click

Imagine having 3 different lists: List 1: bus, plane List 2: [related to bus] slow, can't fly List 3: [related to plane] fast, can fly In my Ionic Angular project, I have successfully implemented the first ion-list. How can I dynamically change th ...

Ways to keep the position of an expanded collapsible table from Material UI intact

I found a collapsible table code snippet on this website: https://mui.com/material-ui/react-table/#collapsible-table However, there seems to be an issue where when I expand a row, the table "grows up" as it increases in size. This behavior is not ideal. I ...

Changing a complex array structure in javascript into a CSV format

I have a complex nested array that I need to convert into a downloadable CSV file. My current approach involves iterating through each array and subarray to build the CSV, but I'm wondering if there's a more efficient method available? Here is a ...

Creating a dynamic full-width background image that adjusts its height according to the content: a step-by-step guide

Currently, I'm attempting to apply a background image to a webpage that spans 100% width in order to adjust to the viewport size. The method I am using involves placing an image directly after the body tag with the subsequent styling: img#background ...