Styling a React button component with Radium

Phil Holden
InstructorPhil Holden

Share this video with your friends

Send Tweet
Published 7 years ago
Updated 4 years ago

React's inline styles allow components to stand on their own by not requiring any external CSS. However HTML's style attributes don't support pseudo selectors like :hover and :active. By using Radium to listen to mouse events we can restore :hover and :active selectors to inline styles.

[00:00] I'm going to get hold of React in Radium. Now I'm going to create a root element for React to render into. I'm going to set JS bin into [inaudible] mode. This is going to give me ES 6 and JS X. I'm going to need render from React and to get hold of that root element I created.

[00:22] I'm going to create a button component. I'm using an arrow function to do that. Let's try rendering that into the root element that we created early. Let's use destructuring to create more space. I'm going to add a style property to my button and create a style object to pass into this.

[00:42] This is very similar to CSS except where you'd expect to have a dash in CSS you need to use CamelCase because it's JavaScript plain objects. You need to wrap your colors and string values in quotes.

[00:55] For simple heights and widths, you can use plain numbers, and React will add in a px for you. But if you've got a complex thing like this padding where I've got two values, I need to use px there.

[01:09] One of the problems with in-line styles is that we can't use pseudo selectors like active and hover. To get round this, we're going to wrap our component in Radium. Behind the scenes, Radium listens to mouse clicks, mouse in, and mouse out. Then it triggers the appropriate styles that we nest within our style object. Now we can hover our button.