Skip to content
Advertisement

Why cant I export and use my custom js styles?

This my main class

import React, { Component } from 'react';
import { withStyles } from '@material-ui/core/styles';
import styles from './FoodStyles';

class Food extends Component {
  render () {
    return (   
      <div>
        <h2 className="header">Food</h2> 
      </div>
    )        
  }   
}

export default withStyles(styles) (Food);

And this is my style class called FoodStyles.js

const styles = theme => ({  
  header: {
    backgroundColor: 'red'
  },
});

export default styles;

They both are in the same folder but still styles cannot be accessed

Advertisement

Answer

This could be the solution to your problem: (You need destructuring as done in line 7 for your styles to be used in your file.) With React, which fully embraces the ES6 syntax, destructuring adds a slew of benefits to improving your code.

Food.js:

import React, { Component } from 'react';
import { withStyles } from '@material-ui/core/styles';
import styles from './styles';

class Food extends Component {
  render () {
    const { classes } = this.props;
    return (   
      <div>
        <h2 className={classes.header}>Food</h2> 
      </div>
    )        
  }   
}

export default withStyles(styles)(Food);

styles.js:

const styles = theme => ({  
    header: {
      backgroundColor: 'red'
    },
  });
  
  export default styles;

Result: enter image description here

Reasons to destructure:

1. Improves readability:
This is a huge upside in React when you’re passing down props. Once you take the time to destructure your props, you can get rid of props / this.props in front of each prop.

2. Shorter lines of code:
Insead of:

var object = { one: 1, two: 2, three: 3 }
var one = object.one; 
var two = object.two; 
var three = object.three
console.log(one, two, three) // prints 1, 2, 3

We can write:

let object = { one: 1, two: 2, three: 3 }
let { one, two, three } = object;
console.log(one, two, three) // prints 1, 2, 3

3. Syntactic sugar:
It makes code look nicer, more succinct, and like someone who knows what they’re doing wrote it.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement