3 • 17 • 22 natesymer
Sometimes, it's necessary to write a bunch of React components in one file. Ideally, that's not how it's done, but sometimes (and for some people) this isn't feasible in the initial steps of writing code. Most code I've seen handles styles in one of the following ways:
Way #1
const style = {
element: { /* ... */ },
anotherElement: { /* .... */}
};
const MyComponent = props => {
return <>
<div style={style.element} />
<div style={style.anotherElement} />
</>;
}
Way #2
Basically the same as #1, except the style object is imported via webpack or similar from another file.
Way #3
const MyComponent = props => {
return <>
<div style={{width: "fuck it"}} />
<div style={{height: "no time for code quality"}} />
</>;
}
Way #4
This one makes me wince with the amount of coupling between the two:
const style = {
// MyComponent
element: { /* ... */ },
anotherElement: { /* .... */}.
// MyOtherComponent
foo: { /* .... */ }
};
const MyComponent = props => {
return <>
<div style={style.element} />
<div style={style.anotherElement} />
</>;
}
const MyOtherComponent = props => {
return <>
<div style={style.foo} />
</>;
}
So naturally, I think I've stumbled upon a better way to write hackjob React components: .bind()
. In other (object-oriented) contexts, you've certainly used this
. Using .bind()
isn't something that isn't obvious when you're writing functional components. And obviously enough, any object - even {}
- can be passed to .bind()
. To bring everything full circle, you can pass your styles to .bind()
. Check this out:
const MyComponent = (function(props) {
return <>
<div style={style.element} />
<div style={style.anotherElement} />
</>;
}).bind({
style: {
element: { /* ... */ },
anotherElement: { /* .... */}
}
});
Two important (and obvious) things to note:
- This doesn't work with arrow functions, but who cares?
- Avoid holding state in the bound object (use
useState
instead)
This has the advantage of keeping the styles local, in the same bit of code as the component, and it saves a lot of compute resources when your code doesn't keep re-creating the same constant objects that hold your styles.