1

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/

1
  • what about conditional rendering then?
    – Sagiv b.g
    Aug 12, 2017 at 18:33

2 Answers 2

2

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

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.

1
  • How I think it works: It will be execute the console.log because the component is actually rendered, but set to invisible by style... I discovered this while searching for an answer to the most optimized way to use 'heavy' modals => conditional rendering seems the best method if you'd ask me! the visible prop hides the modal from the user by making it invisible, including it in each render of the component is is located in, even without it being shown!
    – WiRa
    Oct 3, 2019 at 9:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.