Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React hooks not working when imported from local library

I'm using React to import a function with a useState hook and that seems to break it. I have a version of react with hooks:

npm ls react => [email protected]
npm ls react-dom => [email protected]

I can use components fine. When I include a hooks, I get the "Invalid hook call" screen.

In my library project I have:

/**
 * @class ExampleComponent
 */

import * as React from 'react'

import styles from './styles.css'

export default function ThingyDefault() {
  return <p>hi</p>
}

export type Props = { text: string }

export class ExampleComponent extends React.Component<Props> {
  render() {
    const {
      text
    } = this.props

    return (
      <div className={styles.test}>
        Example Component: {text}
      </div>
    )
  }
}

////////////////// THIS DOESN'T SEEM TO WORK //////////////////
export function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = React.useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

In my project that uses that library:

import React from 'react';
import './App.css';
import ThingyDefault, {ExampleComponent, Example} from 'thingy';

const App: React.FC = () => {
  return (
    <div>
    <ThingyDefault />
    <ExampleComponent text='hello' />

    {/* commenting this component out makes it work */}
    <Example />
    </div>
  );
}

export default App;

What am I doing wrong here?

like image 741
Ugtemlhrshrwzf Avatar asked Dec 19 '25 21:12

Ugtemlhrshrwzf


1 Answers

Since it seems to be a import/export issue, try changing your export to this:

const Example = () => {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = React.useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}
export { Example };
like image 154
Brian Thompson Avatar answered Dec 21 '25 14:12

Brian Thompson