|
| 1 | +import React, { useState } from 'react'; |
| 2 | +import type { Meta, StoryObj } from '@storybook/react'; |
| 3 | +import { Search } from '../Search'; |
| 4 | +import { Box } from '../../Box/Box'; |
| 5 | +import { Text } from '../../Text/Text'; |
| 6 | + |
| 7 | +const meta: Meta<typeof Search> = { |
| 8 | + title: 'Components/Search', |
| 9 | + component: Search, |
| 10 | + args: { |
| 11 | + results: ['Adam', 'Barry', 'Charles', 'David'] |
| 12 | + } |
| 13 | +}; |
| 14 | + |
| 15 | +export default meta; |
| 16 | + |
| 17 | +type Story = StoryObj<typeof Search>; |
| 18 | + |
| 19 | +export const Default: Story = {}; |
| 20 | + |
| 21 | +export const WithPlaceholder: Story = { |
| 22 | + args: { |
| 23 | + placeholder: 'Search by name' |
| 24 | + } |
| 25 | +}; |
| 26 | + |
| 27 | +export const Disabled: Story = { |
| 28 | + args: { |
| 29 | + disabled: true |
| 30 | + } |
| 31 | +}; |
| 32 | + |
| 33 | +export const WithAPI: Story = { |
| 34 | + args: { |
| 35 | + width: '20rem', |
| 36 | + placeholder: 'Enter a name' |
| 37 | + }, |
| 38 | + parameters: {}, |
| 39 | + argTypes: { |
| 40 | + results: { table: { disable: true } } |
| 41 | + }, |
| 42 | + render: args => { |
| 43 | + const [results, setResults] = useState<JSX.Element[]>([]); |
| 44 | + |
| 45 | + const mapName = ({ name }: { name: string }, index: number) => ( |
| 46 | + <Box key={`${name}-${index}`} height="2.5rem" display="flex" alignItems="center"> |
| 47 | + <Text marginLeft="1rem">{name}</Text> |
| 48 | + </Box> |
| 49 | + ); |
| 50 | + |
| 51 | + const fetchCharacter = async (name: string) => { |
| 52 | + const response: { results: { name: string }[] } = await ( |
| 53 | + await fetch(`https://swapi.dev/api/people/?search=${name}`) |
| 54 | + ).json(); |
| 55 | + setResults(response.results?.map(mapName)); |
| 56 | + }; |
| 57 | + |
| 58 | + return ( |
| 59 | + <Search |
| 60 | + {...args} |
| 61 | + results={results} |
| 62 | + onInputChange={name => fetchCharacter(name)} |
| 63 | + onClear={() => setResults([])} |
| 64 | + /> |
| 65 | + ); |
| 66 | + } |
| 67 | +}; |
0 commit comments