0

I've been trying to create a React HOC that will apply the corresponding styles to any component pass to it.

My idea was to do something similar to this

// Button.css.js const styles = {backgroundColor:"blue"} // Button.js const Button = (props) => <button {...props}/> // applyStyles.js const applyStyles = (Component) => (props) => { const styles = import style from `${Component.name}.css` return <Component {...props} style={styles} /> } 

I know applyStyles contains invalid syntax but is just to illustrate what is what I'm trying to do.

If any of you have a way around this I will really appreciate it.

1
  • This feels like a very odd abstraction. What's wrong with simply importing styles directly into the component? Commented Jun 22, 2021 at 2:58

3 Answers 3

1

You can try this

import (`/pathTofile/${Component.name}.css`) .then(data => { // rest of the code goes her })

Sign up to request clarification or add additional context in comments.

1 Comment

this might work but this would mean that you have to lazyload this component everytime you reuse it
0

My recommendation is that you use styled-component for this:

const Wrapper = styled.div` > * { backgroundColor:"blue" }` function AppyStylesHOC(Component) { return (props) => { return (<Wrapper> <Components {...props} /> </Wrapper> }) } 

Comments

0

You can try this:

Button.js

import React from 'react'; import styles from './Button.module.css'; const Button = props => { return ( <button className={styles.button} type={props.type || 'button'} onClick={props.onClick} > {props.children} </button> ); }; export default Button; 

Button.module.css

.button { font: inherit; border: 1px solid #4f005f; background: #4f005f; color: white; padding: 0.25rem 1rem; cursor: pointer; } 

App.js

import Button from '../Button'; ... <Button type="submit">+ Add</Button> ... 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.