Home > Software engineering >  How to call a class component with a variabel?
How to call a class component with a variabel?

Time:03-30

I have this function, with a headline. How can I call something like:

<LayerEditPost test={"It works!"} /> so that my {this.state.test} changes?

In functional components, I can pass properties to call my components, but it does not work with class components ( Property 'test' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes & Readonly<{}>)

I am not sure where I have to declare my variable so that I am able to receive a value from the component call.

export class LayerEditPost extends React.Component<{}, {test: string, open: boolean}> {
    constructor(props) {
        super(props);
        this.state = { open: false, test: "hi" };
        this.toggleDrawer = this.toggleDrawer.bind(this);
    }

    toggleDrawer(e) {
        console.log("click", e);
        this.setState({ open: !this.state.open });
    }

    render() {
        return (
            <>
                <IconLink icon={object___pencil} iconVariant={"solid"} onClick={this.toggleDrawer}></IconLink>
                <Layer
                    layout={"right-75"}
                    closeLinkLabel={"Back to Administration"}
                    open={this.state.open}
                    onCloseClick={this.toggleDrawer}
                    htmlAttrs={{
                        "aria-labelledby": "layerLeftLabel",
                        "aria-describedby": "layerLeftDescription",
                    }}
                >
                    <H2 id="layerLeftLabel">Edit Post</H2>
                    <H2>{this.state.test}</H2> <- I want to call LayerEditPost with a variable to change "test"
                </Layer>
            </>
        );
    }
}

CodePudding user response:

In your React.Component<{}, {test: string, open: boolean}> definition at the first line, you have two generic types: The second one is the type for your state and the first one ({}) for the properties you are looking for.

You can move your test: string definition to the first object type, so that your definition becomes

export class LayerEditPost extends React.Component<{test: string}, {open: boolean}> { /* ... */ }

Then you can access the passed property using this.props.test:

export class LayerEditPost extends React.Component<{test: string}, {open: boolean}> {
    render() {
        return (
            <>
                {/* Other stuff ... */}
                <H2>{this.props.test}</H2> <- I want to call LayerEditPost with a variable to change "test"
            </>
        );
    }
}
  • Related