Jonny B
Jonny B

Reputation: 720

Material-UI withStyles not adding classes to props

I'm trying to implement some styling using Material-UI's withStyles method, however I'm not able to get classes as a prop. Any suggestions as to what I'm missing? I've included the relevant code below, but note that there is an <App> component in this file that I'm leaving out for brevity.

import React from 'react'
import ReactDOM from "react-dom";
import {Paper, Typography} from '@material-ui/core'
import {withStyles} from '@material-ui/core/styles'
import NavBar from "./navBar";

class Recipe extends React.Component {
    constructor(props) {
        super(props);
    }

    componentDidMount() {
        console.log('Recipe Did Mount')
    }

    render() {
        const {recipeData, classes} = this.props;
        return (
            <Paper>
                <Typography className={classes.recipeName}>{recipeData.name}</Typography>
                <Typography className={classes.recipeIngredients}>{recipeData.ingredients}</Typography>
                <Typography className={classes.recipeInstructions}>{recipeData.instructions}</Typography>
            </Paper>
        )
    }
}

const styles = {
    root: {
        fontSize: "1.0rem",
        margin: "0px"
    },
    recipeName: {
        fontSize: "1.0rem",
        margin: "0px"
    },
    recipeIngredients: {
        fontSize: "1.0rem",
        margin: "0px"    },
    recipeInstructions: {
        fontSize: "1.0rem",
        margin: "0px"    }
};

withStyles(styles)(Recipe);

document.addEventListener('DOMContentLoaded', () => {
    ReactDOM.render(
        <App/>,
        document.body.appendChild(document.createElement('div')),
    )
});

Upvotes: 1

Views: 1652

Answers (2)

Kumar Nitesh
Kumar Nitesh

Reputation: 1652

Assuming App is defined in a separate file (for others who may come looking for this question), change the

`withStyles(styles)(Recipe);`

To

export default withStyles(styles)(Recipe);

As Ryan already explained ' withStyles is the higher order component that creates and returns a new component'

Upvotes: 0

Ryan Cogswell
Ryan Cogswell

Reputation: 81136

Since you aren't setting withStyles(styles)(Recipe); into a variable, I suspect you must be using Recipe directly within App.

withStyles doesn't change Recipe. withStyles creates a new component that wraps Recipe and passes the classes prop to it. In order to see the classes prop, you need to use the newly-created component with something like the following:

const StyledRecipe = withStyles(styles)(Recipe);
const App = ()=> {
   return <StyledRecipe/>;
}

Upvotes: 5

Related Questions