0

I'm just starting with React, and was trying to practice by creating a simple page with a button that show the Modal component when clicked... But I'm running into a Error: Too many re-renders. React limits the number of renders to prevent an infinite loop. and I stucked there, I can't find what's wrong.

Can someone please help me?

Index.js

import React from 'react';
import ReactDOM from 'react-dom';

import View from './View'

ReactDOM.render(
  <React.StrictMode>
    <View />
  </React.StrictMode>,
  document.getElementById('root')
);

View.js

import React from 'react';
import Modal from './Modal.js';

const View = () => {
    let [showModal, setModal] = React.useState(false)
    return(
        <>
            {showModal ?? <Modal />}
            <button onClick={setModal(!showModal)}>
                Mostrar modal
            </button>
        </>
    )
}

export default View;

Modal.js

import React from 'react';

const Modal = () => {
    return(
        <div>
            <h1>Modal</h1>
            <p>Mostrando o modal</p>
        </div>
    )
}

export default Modal;
  • 1
    You need to pass a **function** to `onClick` and not the return value of `setModal(!showModal)` – Quentin Mar 26 '21 at 08:28

1 Answers1

0

You accidentally invoke the state change (triggering a render recursively) when trying to pass your onClick handler here (instead passing the return value of the function invocation):

<button onClick={setModal(!showModal)}>

Instead, pass a function that can get invoked on click:

<button onClick={() => setModal(!showModal)}>
m90
  • 11,434
  • 13
  • 62
  • 112