E
E
Enma2022-01-28 21:02:40
JavaScript
Enma, 2022-01-28 21:02:40

How to use states inside a UI component?

In general, I decided to make a small UI library for myself, for example, on Tailwind.
I have it in a separate NPM package or connected via npm link.

There are a couple of situations when a component should have its own local state, the question is how to implement this?

I have functional components like:

func

import React, { useState } from "react";

export const TestBlock = () => {
    const [state, setState] = useState(null);

    return (
        <button onClick={() => setState(Date.now())}>
            blablabla
        </button>
    )
}


All this magnificence falls because
"Invalid hook call. Hooks can only be called inside of the body of a function component" and so on.

At the same time, the component on the classes is ok.
class

import React from "react";

export class TestBlockClass extends React.Component<{}, { timestamp: number }> {

    constructor(props: any) {
        super(props);
        this.state = { 
            timestamp: 0
        };
    }

    render() {
        return (
            <>
                <div>
                    Time {this.state.timestamp}
                </div>
                <button onClick={() => this.setState({timestamp: Date.now()})}>
                    тык
                </button>
            </>
        )
    }
}



What to do, how to be?
Or all the same to use classes?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
E
Enma, 2022-01-28
@Enma

in general, the problem is in npm link
to solve it, you need to add in the webpack config:

resolve: {
        extensions: [".ts", ".tsx", ".js"],
        alias: {
            react: path.resolve('./node_modules/react'),
        },
    },

A
Alexander, 2022-01-28
@Seasle

https://codesandbox.io/s/qna-q-1107640-miil1 is not reproduced, so something was not said.

A
Aetae, 2022-01-28
@Aetae

You have to do with it <TestBlock/>or React.createElement(TestBlock), and somewhere you do just TestBlock().

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question