Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to stop a component from recursively showing up in react Typescript

I have a parent component Form that has a button where on user click, it will display a child component MyWindow. The MyWindow component also has the Form component so the button will appear in MyWindow as well. How can I stop the Button from displaying in MyWindow when it’s open? I only want the Button to appear in the parent Form.

// parent component --------
interface State {
    showWindow: boolean;
}

export class Form extends React.Component<Props, State> {
    constructor(props: Props) {
        super(props);
        this.state = {
            showWindow: false,
        };
    }

    public render() {
        return (
            <div>
                <Button
                    onClick={() => this.setState({ showWindow: true })}
                >
                    Show Window
                </Button>
                {this.state.showWindow && (
                    <MyWindow/>
                )}
            </div>
        );
    }
}

// child component --------

interface Props {}

export const MyWindow: React.FC<Props> = props => {
    return (
        <Window>
            <Form/>
        </Window>
    );
};

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You could add a prop to your child component to know that it is inside form:

// parent component --------
interface ParentProps {
    isInside?: boolean;
}

interface State {
    showWindow: boolean;
}

export class Form extends React.Component<ParentProps, State> {
    constructor(props: Props) {
        super(props);
        this.state = {
            showWindow: false,
        };
    }

    public render() {
        return (
            <div>
               {!isInside && (
                <Button
                    onClick={() => this.setState({ showWindow: true })}
                >
                    Show Window
                </Button>)}
                {this.state.showWindow && (
                    <MyWindow/>
                )}
            </div>
        );
    }
}

// child component --------

interface Props {}

export const MyWindow: React.FC<Props> = props => {
    return (
        <Window>
            <Form isInside />
        </Window>
    );
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading