1

I have inherited some code and I've been manipulating it, but I came across something that makes me scratch my head.

I am not sure whether the issue I am having relates to specifically to react.js or more generally to CSS / javascript...

In this code, we make use of react.js withStyles.

I have set up a sandbox to demonstrate.

First thing in the file, we define some styles that can then be applied to page elements, e.g.

const styles = theme => ({
  buttonGroup: {
    width: "250px",
    display: "flex",
    flexWrap: "wrap",
  }, ...

then, when we define a class, we can get access to these styles by doing a const { classes } = this.props , e.g.

class MyButtons extends React.Component {
  render() {
    const { classes } = this.props;
    return (
      <div className={classes.buttonGroup}>
        {three_buttons.map(e => (
          <Button className={classes.a_button}>{e}</Button>
        ))}

      </div>
    );
  }
}

That is all fine and works. What I've tried is to, in the same file, define a second class, which I then call from the first (to make a component within a component).

However, the const { classes } = this.props does not seem to gain me access to the styles defined at the top, and when I try to set className={classes.buttonGroup} in the second class, I get an error

TypeError: read property 'buttonGroup' of undefined

I am pretty sure I can overcome this by simply defining the second class in a separate file like I usually do, but I would like to understand why this does not work.

levraininjaneer
  • 1,157
  • 2
  • 18
  • 38

1 Answers1

2

You are not passing the styles as props to MyOtherButtons Component and hence you are getting this issue. Pass the classes as props and things would work as expected. It works for MyButtons component since you are passing the styles using withStyles syntax.

Check the working link https://codesandbox.io/s/m3rl6o2qyj

cdoshi
  • 2,772
  • 1
  • 13
  • 20
  • OK thanks! But, I still wonder: why did I not have to pass styles in the first class? When I create the MyButtons object (on index.js), I pass no classes. The style definition on MyButtons seems to "automatically" apply to MyButtons, but not to MyOtherButtons? Why is this? – levraininjaneer Jul 29 '18 at 06:11
  • You are actually passing the styles to MyButtons using the syntax withStyles(styles)(MyButtons). Remove that and it will stop working even for MyButtons – cdoshi Jul 29 '18 at 06:12
  • Aha! But then why does it not work (in the original scenario) to simply do `export default withStyles(styles)(MyButtons, MyOtherButtons);` ? Is it because MyOtherButtons is called from within MyButtons, and therefore does not "pass through" the export statement before being called? I checked and it seems this is the case. https://codesandbox.io/s/pm1x0q5w7m. Thanks a lot! – levraininjaneer Jul 29 '18 at 06:51