On click returns null instead of an object

Viewed 190

It's really basic I guess. I'm trying to add onClick callback to my script & I believe I'm missing a value that would be responsible for finding the actual item.

Main script

import React from 'react';
import { CSVLink } from 'react-csv';
import { data } from 'constants/data';
import GetAppIcon from '@material-ui/icons/GetApp';
import PropTypes from 'prop-types';

const handleClick = (callback) => {
    callback(callback);
};

const DownloadData = (props) => {
    const { callback } = props;
    return (
        <>
            <CSVLink
                data={data}
                onClick={() => handleClick(callback)}
            >
                <GetAppIcon />
            </CSVLink>
        </>
    );
};

DownloadData.propTypes = {
    callback: PropTypes.func.isRequired,
};

export default DownloadData;

Storybook code

import React from 'react';
import DownloadData from 'common/components/DownloadData';
import { data } from 'constants/data';
import { action } from '@storybook/addon-actions';

export default {
    title: 'DownloadData',
    component: DownloadData,
};

export const download = () => (
    <DownloadData
        data={data}
        callback={action('icon-clicked')}
    />
);

So right now with this code on click in the storybook I'd get null and I'm looking for an object.

1 Answers

One of the potential issues I can see is that your handleClick function is stored as it is in-memory, when you import the component. That means you're keeping reference of something that doesn't exists and expects to use it when rendering the component with the callback prop.

Each instance of a component should have its own function. To fix it, move the function declaration inside the component. Like this:

const Foo = ({ callback }) => {
  // handleClick needs to be inside here
  const handleClick = callback => {
    console.log("clicked");
    callback(callback);
  };

  return <div onClick={() => handleClick(callback)}>Click me!</div>;
};

Check this example.

If this doesn't fix your problem, then there is something wrong with how you're implementing Storybook. Like a missing context.

Related