Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I write a storybook story for a component that has redux-connected component as grandchild?

We are building a Storybook UI library from our existing code base. The code wasn't written with component driven development in mind. There are many instances where a component renders descendants that are connected to the Redux store.

E.g., Parent (connected) -> Child (unconnected) -> Grandchild (connected)

Now if I'm building a story for Parent, I understand how to pass hard-coded data as a prop to an immediate child component in order to avoid Redux all together. However, I can't figure out how to do this when the connected component is more deeply nested.

Ideally I don't want to have to use Redux at all for stories, but even if I do initialize a Redux store and wrap the parent component in a Provider as described here, would this even work to connect the grandchild component?

Any ideas would be helpful.

like image 665
Avi C Avatar asked Oct 30 '19 14:10

Avi C


People also ask

Can we use Redux connect in functional component?

As of version 7.1, Redux supports React Hooks, meaning you can use Redux with Hooks in your functional components instead of using Redux connect() .

Can I pass multiple components within connect Redux?

Since you can have only one default export, you'd have to use named export in this case or split up those two components in two files.

How does a Redux connected component know when to re render?

It deduces the changes of your data by running the reducer function you provide, and returns the next state that corresponds to every action dispatched. React Redux then optimizes component rendering and makes sure that each component re-renders only when the data it needs change.


1 Answers

If you want to solve the problem within your story file (and just fetch your store), use decorator like this:

import React from "react";
import { Provider } from 'react-redux'
import Parent from "./Parent";

import { store } from "../../../redux/store";

export default = {
  title: "pages/Parent",
  component: Parent,
  decorators : [
    (Story) => (<Provider store={store}><Story/></Provider>)
  ]
};

Sidenote, if this gives you the error useNavigate() may be used only in the context of a <Router> component., then you may need <MemoryRouter><Provider store={store}><Story/></Provider></MemoryRouter> (import {MemoryRouter} from 'react-router-dom')

like image 127
Roman Avatar answered Oct 22 '22 19:10

Roman