Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React class components - conditional styling based on props

I'm working with older versions of material-ui with no possibility to upgrade.

I am trying to change the background of the Paper component based on a few combinations of the props. I don't think it's complicated to require use of the makeStyles HOC. Is this possible?

I think the problem is this line: classes={{ root: correctBackgroundColor.root }}

but the documentation on the https://v0.material-ui.com/#/components/paper unhelpfully says "Other properties (not documented) are applied to the root element."

import React from "react";

const correctBackgroundColor = {
  root: {
    width: 30,
    height: 30,
    border: "1px solid lightgrey",
    backgroundColor: props => {
      if (props.ledIsOn === true && props.ledColorType === "Green") {
        return "#00FF00";
      }
      if (props.ledIsOn === true && props.ledColorType === "Orange") {
        return "#FFA500";
      } 
    }
  }
};

class ColorChange extends React.Component {
  render() {
    const { classes } = this.props;
    let textToRender = (
      <Paper
        id={this.props.id}
        classes={{ root: correctBackgroundColor.root }}
      />
    );
    return (
      <div>
        <Typography variant="p" className={classes.typography_root}>
          {this.props.textLabel}
        </Typography>
        {textToRender}
      </div>
    );
  }
}

export default withStyles(styles)(ColorChange);

there is a sandbox at : https://codesandbox.io/s/adoring-bell-oyzsn TIA!

like image 389
tmc Avatar asked Jul 15 '20 10:07

tmc


People also ask

How do you apply style based on condition in React?

Create a new react application or open existing react app. Declare two different CSS style objects named as objectStyle and objectStyleValid with below attributes (in Code). Next we will declare a const variable named “isValid”. Based on its value (true/false) we will try to change the CSS style.

Can I pass props to styled component?

To pass props to React components created with styled-components, we can interpolate functions into the string that creates the component. We create the ArrowStyled component with the styled. div tag. Then string that we pass into the tag has the rotate value set from a prop.

What is conditional styling in React?

What Is Conditional Styling? In simple words, it is changing CSS based on a set of conditions or a state. The CSS that will be changed and/or added based on a condition can be inline styles or styled components among the many different ways of adding CSS in React.

Can props be pass to a class component?

As said, there is no way passing props from a child to a parent component. But you can always pass functions from parent to child components, whereas the child components make use of these functions and the functions may change the state in a parent component above.

How to conditionally add props in a React component?

Now, let's see all the different ways we can conditionally add props in our react component: Setting a property/attribute value as undefined or null does not show that property in the DOM. We can use that with the ternary operator to conditionally add a property like so:

How to change the CSS based on condition in react?

The CSS that will be changed and/or added based on a condition can be inline styles or styled components among the many different ways of adding CSS in React. Let's say we have a toggle menu, in this case conditional styling will be used to show/hide the menu based on a state. Similarly, we can open and close a popup using this method too.

How do you define a class component in react?

Function and Class Components. The simplest way to define a component is to write a JavaScript function: function Welcome(props) { return <h1>Hello, {props.name}</h1>; }. This function is a valid React component because it accepts a single “props” (which stands for properties) object argument with data and returns a React element.

Is everything in react all about props and state?

I think it’s fair to say that everything in React revolves around props and state. If you’re a relatively young engineer then chances are that you have not been exposed to working with class components as much as you should have.


Video Answer


1 Answers

I hope i got you right. There are two things you should put attention to:

First, correctBackgroundColor does not recognize props because this is out of scope, therefore, I would recomment to change it into a function, pass the props to it, and make the function return a style object.

Second thing, I would use style when applying the object to Paper, so the style of that paper would be a call to correctBackgroundColor with the props, like this:

<Paper id={this.props.id} style={correctBackgroundColor(this.props)} />

Final code:

import React from "react";
import withStyles from "@material-ui/core/styles/withStyles";
import Typography from "@material-ui/core/Typography/Typography";
import Paper from "@material-ui/core/Paper/Paper";

const styles = theme => ({
  typography_root: {
    fontSize: 12,
    margin: 10
  }
});
const correctBackgroundColor = props => {
  let bgSwitch = "none";
  if (props.ledIsOn === true && props.ledColorType === "Green")
    bgSwitch = "#00FF00";
  if (props.ledIsOn === true && props.ledColorType === "Orange")
    bgSwitch = "#FFA500";
  if (props.ledIsOn === true && props.ledColorType === "Red")
    bgSwitch = "#FF0000";
  if (props.ledIsOn === true && props.ledColorType === "Grey")
    bgSwitch = "lightGrey";
  return {
    width: 30,
    height: 30,
    border: "1px solid lightgrey",
    backgroundColor: bgSwitch
  };
};

class ColorChange extends React.Component {
  render() {
    const { classes } = this.props;
    let textToRender = (
      <Paper id={this.props.id} style={correctBackgroundColor(this.props)} />
    );
    return (
      <div>
        <Typography variant="p" className={classes.typography_root}>
          {this.props.textLabel}
        </Typography>
        {textToRender}
      </div>
    );
  }
}

export default withStyles(styles)(ColorChange); //with styles injects classes props with styles contained.

Code Sandbox

like image 146
SomoKRoceS Avatar answered Oct 17 '22 09:10

SomoKRoceS