'React Component - Cannot read properties of null (reading 'useState')

I am building a little local dev/testing/documentation environment for some components which are used across different projects and so want to create them as individual npm packages.

Everything was working perfectly until I tried to use useState() in one of the components. Add this created the following errors:

Invalid hook call. Hooks can only be called inside of the body of a function component.
TypeError: Cannot read properties of null (reading 'useState')

I feel this is strange and I can't figure out what is causing it. I also tested with other hooks to see if it was just useState that was the problem but others such as useEffect and useRef also have the same problem.

Project structure is:

/components (the components to develop/test/document
    /component-group
        /Component
            index.js
            Component.js
            component.scss
            package.json
/library  (where all the components are developed/tested/documented)
    /component1
    /component2
    /etc (all the components that make up the library)
webpack.config.js
package.json
etc...

Components are imported into the library using a relative path because I don't won't to have to publish them to npm and update the version locally every time a change is made and needs to be tested.

As for the code for the component where useState is causing problems, this is a basic version which still causes problems:

import React, { useState } from 'react';

const TestComponent = () => {

    const [testState, setTestState] = useState("testing");

    return (
        <p>Hello World</p>
    )

}

export default TestComponent

If I comment out the useState line then Hello World is displayed, if I uncomment the line then the errors appear.

Any ideas as to what might be wrong would be really appreciated.

Thank you in advance!



Solution 1:[1]

Does this work?

<a href ="[LINK]" ></a>

Copy the link you need, and put it instead of [LINK]

Solution 2:[2]

The answer is pretty simple. Assuming you have your URL in a metafield, just render the value into the href.

<a href="{{ someresource.metafields.mylinks.url }}" />

Since you did not specify which resource you speak of, I left it as someresource. If it is pages, the use pages. mylinks is your namespace where you stored your metafield key values. The key is url, and the value is whatever you stored there, a link to another page maybe.

Shopify has a ton of documentation on using Metafields, you can refer to those for more details.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Okid 62
Solution 2 David Lazar