U
U
uRoot2020-09-19 16:04:29
React
uRoot, 2020-09-19 16:04:29

How to correctly assign a class to an active button in React/Redux?

There is a smart component and stupid. Buttons are rendered in stupid:

spoiler
5f66005cd0d7d369412457.png

The stupid component itself looks like this:
import React from 'react';
import Card from '@material-ui/core/Card';
import CardActions from '@material-ui/core/CardActions';
import CardContent from '@material-ui/core/CardContent';
import Button from '@material-ui/core/Button';
import Typography from '@material-ui/core/Typography';
import style from './method.module.scss'
import {useDispatch} from "react-redux";
import {getMethod} from "../../redux/action";


export default function Method({title, description, name}) {
  const dispatch = useDispatch()

  return (
    <Card className={style.method}>
      <CardActions>
        <Button
          name={name}
          className={style.button}
          size="small"
          onClick={(event) => dispatch(getMethod(event.currentTarget.name))}
        >
          <CardContent>
            <Typography variant="h5" component="h2">
              {title}
            </Typography>
            <Typography  color="textSecondary">
              {description}
            </Typography>
          </CardContent>
        </Button>
      </CardActions>
    </Card>
  );
}


The getMethod action gets the name of the button and writes it to the store:
export function getMethod(method) {
  return {
    type: REQUES_METHOD,
    payload: method
  }
}


I can't figure out where the logic for setting the active class to the active button should be. How to properly organize logic without breaking React/Redux patterns?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry, 2020-09-19
@uroot

A smart component should read the property from the store where the name of the button is written and pass a boolean value to the stupid Method component, which, depending on this stupid value, adds the active class to the button or not.

export default function Method({title, description, name, isActive}) {

...
       <Button
          name={name}
          className={style.button + (isActive ? ' active-class' : '')}

Or, as an option, pass activeName to Method and compare there already
export default function Method({title, description, name, activeName}) {
  const isActive = name === ActiveName 
...
       <Button
          name={name}
          className={style.button + (isActive ? ' active-class' : '')}

But in general, saving the active button in the store does not seem obvious, it is possible to store the name of the active button in the state of the smart component, because the store is needed when you need to save the value of the active button between component calls or when you need to pass it to other components.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question