Introduction and Installation of Storybook for React
Last Updated :
24 Nov, 2023
Storybook is an open-source UI development tool that facilitates the creation of reusable, well-documented components independently. It automates visual testing to prevent bugs and runs alongside the app in development mode. Additionally, it supports server-rendered component frameworks like Ruby on Rails.
Prerequisites:
Features:
- Implement components and pages without needing to work on the backend, It runs independently.
- It visually tests your components.
- It is efficient for the developers working in a team, as one gets all the proper code and documents of the component properly structured.
- It is free of cost and open to everyone.
- Easy to install and to work with.
- It works as a UI explorer.
- Supports a wide range of tech stacks.
Steps to Create the React Application And Installing Module:
Step 1: Create the react project folder
npm create-react-app projectstorybook
Step 2: Change your directory to the newly created folder by using the following command.
cd projectstorybook
Step 3: To add storybook in your project, in your terminal write the command
npm sb init
Project Structure:
The updated dependencies in package.json file will look like:
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4",
}
Example: Let’s create a component named WelcomeText that will show “Welcome to GeeksForGeeks” in two colors one is primary i,e green, and another one black named secondary. Let’s create a folder named Components inside the folder create files such as WelcomeText.js,WelcomeText.css and WelcomeText.stories.js. and write the below-mentioned codes respectively.
Javascript
import React from 'react'
import "./WelcomeText.css"
function WelcomeText (props) {
const { variant = 'primary' , children, ...rest} = props
return (
<h1 className={`heading ${variant}`} {...rest}>
{children}
</h1>
)
}
export default WelcomeText
|
Javascript
import React from 'react' ;
import WelcomeText from './WelcomeText' ;
export default {
title: 'WelcomeText' ,
component: WelcomeText
}
const text = "Welcome to GeeksforGeeks"
export const Primary = () =>
<WelcomeText variant= 'primary' >{text}</WelcomeText>
export const Secondary = () =>
<WelcomeText variant= 'secondary' >{text}</WelcomeText>
|
CSS
.heading {
font-size : 80px ;
font-weight : 900 ;
}
.primary {
color : green ;
}
.secondary {
color : black ;
}
|
Step to run the application: Open the terminal and type the following command.
npm run storybook
Output:
Share your thoughts in the comments
Please Login to comment...