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.
Member comments are a way for members to communicate, interact, and ask questions about a lesson.
The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io
Be on-Topic
Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.
Avoid meta-discussion
Code Problems?
Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context
Details and Context
Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!