Creating a button React component using styled-components

Artem Sapegin
InstructorArtem Sapegin

Share this video with your friends

Send Tweet
Published a year ago
Updated 10 months ago

In this lesson we’ll create a generic button primitive component the has one style, using styled-components.

Let’s discuss the API first.

Our button will have a default state.

<Button onClick={() => console.log('henlo')}>Push me</Button>

Disabled state. Let’s use the disabled prop like on a plain HTML button element, because our button is an extension of the native HTML button and there’s no need to create a new API when a familiar to developers API already exists:

<Button disabled>Can’t touch this</Button>

We also want to make sure our button works as a link too:

<Button as="a" href="/">Push me</Button>

We don’t have to implement as prop because it’s added to every component by styled-components automatically, but we need to make sure styles don’t break with another HTML element.

We’ll use following libraries:

You can either use this lesson’s Git repository or install them manually in your project:

npm install styled-components

Useful links and documentation:

Artem Sapegin: [0:00] Create a new [inaudible] file, Button.md, and add some examples of our button component -- Normal button state, Disabled state, and Button as a link. Then create the component file, button.js, and run styleguidist.

[0:25] Import styled components and PropTypes. Create a new styled component based on the button element and export it. Add PropTypes disabled, which is Boolean, and children, which is the React node and required. Now let's style our button.

[0:58] Then add hover, active and focus styles. We use not(:disabled) here because we don't want disabled button to have hover or active states. We can't use enabled to the class because it wouldn't work with links, but focus is fine as it is. Disabled links can be focused.

[1:23] Also know that even if we're removing the default focus outline, our custom style is significantly different from the normal button state, so focus could use [inaudible] keyboard. Then add disabled state.

[1:40] Now look at the last example here, Button as a link. Something is still wrong here, the underline that's coming from the anchor element should not be here. Let's remove it.