Search code examples
reactjstypescriptreact-hookscomponents

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

  • 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>
        );
    };