Victor
Victor

Reputation: 762

React JS: Avoid the Modal to be executed when the component is rendered

What I've noticed when using Modals in React is when the component is rendered, the body of the Modal is executed even if the visible state is false.

Example:

render() {
        return (
            <Modal
                title="Basic Modal"
                visible={false}
                onOk={this.handleOk}
                onCancel={this.handleCancel}
            >
                <p>Some contents...</p>
                {console.log('visible is false but content is being executed!')}
            </Modal>
        );
    }

I want to execute the entire Modal only if the visible prop is true. Is there a way to do it?

I'm using this basic Modal Component: https://ant.design/components/modal/

Upvotes: 1

Views: 1481

Answers (2)

yesmeck
yesmeck

Reputation: 316

It's not about Modal, it's about the component which renders Modal, when the parent component re-renders, the console.log will always execute.

Upvotes: 0

Sagiv b.g
Sagiv b.g

Reputation: 31024

You can use conditional rendering with the logical && Operator.
You can read more about conditional renders in the Docs.
For example:

render() {
        return (
          SomeCondition &&
            <Modal
                title="Basic Modal"
                visible={true}
                onOk={this.handleOk}
                onCancel={this.handleCancel}
            >
                <p>Some contents...</p>
                {console.log('visible is false but content is being executed!')}
            </Modal>
        );
    }

Upvotes: 2

Related Questions