Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to style a functional stateless component in Reactjs using classes object

I want to write and style a functional stateless component in ReactJs as described here.

const MyBlueButton = props => {
  const styles = { background: 'blue', color: 'white' };  
  return <button {...props} style={styles} />;
};

The problem is that I want to add in some styles from stateful components as described here.

const styles = theme => ({
  root: {
    width: '100%',
    maxWidth: 360,
    backgroundColor: theme.palette.background.paper,
  },
});

The problem is that when I try to do something like this:

<div className={classes.root}>

I get the error:

'classes' is not defined no-undef

How do I access the withStyles classes object to style root the way I want?

like image 671
Let Me Tink About It Avatar asked Oct 05 '18 00:10

Let Me Tink About It


People also ask

Can you define any stateless functional component as a class?

A stateless functional component can be seen just as a function which returns JSX based on the prop values that are passed to it. It is not a class and does not extend the React. Component class. It also has no state.

How do you add a style to a functional component React?

For a React component that you'd like to style, simply create a CSS file that'll contain the styles for that component. At build time local class names are mapped and exported as a JS object literal for React- as well as a modified version of input CSS with renamed class names.

How do you make a stateless component in React?

A functional(a.k.a. stateless) component is just a plain javascript function which takes props as an argument and returns a react element. const MyStatelessComponent = props => React. createElement('div', null, props.name);

Are functional components stateless in React?

A functional component is always a stateless component, but the class component can be stateless or stateful.


1 Answers

If I understood right here is how you can do this with a functional component.

const styles = theme => ( {
  root: {
    width: "100%",
    maxWidth: 360,
    backgroundColor: theme.palette.background.paper,
  },
} );

const App = ( props ) => {
  const { classes } = props;
  return <div className={classes.root}>Foo</div>;
};

export default withStyles( styles )( App );
like image 187
devserkan Avatar answered Sep 19 '22 12:09

devserkan