How can I update a parent status via child in React?

Asked

Viewed 101 times

5

I need to update a parent’s status via a link click on the child’s Komponent, but I’m not getting it.

I’m trying this way:

Component Pai

export default function Home() {
const [board, setBoard] = useState(0);

function hundleGetBoardId(boardId){
    setBoard(boardId);
}


return(
    <div>
        <div id="header">
            
            <Row>
                <Col md={2} className="worksp">
                    <Nav variant="tabs" defaultActiveKey="/home" className="flex-column">
                        
                                 <Colapse 
                                    workspace={workspace.id} 
                                    condicao={true} 
                                    callbackParent={hundleGetBoardId} 
                                />
                   
                        ))}
                    </Nav>
                </Col>

            </Row>

        </div>
        
    </div>
);}

Component Filho

export default function Colapse({ workspace, condicao, callbackParent }) {
const [boards, setBoards] = useState([]);

useEffect(() => {
    api.get(`boards/${workspace}`).then(response => {
        setBoards(response.data);
    })
}, [workspace]);

return(
    <Collapse in={condicao}>
        <ListGroup >
        {boards.map(board => (
            <ListGroup.Item key={board.id} >
                <a href={`#`} onClick={callbackParent(board.id)} >{board.titulo}</a>
            </ListGroup.Item>
        ))}
        </ListGroup>
    </Collapse>
);}

This code is giving the following error:

Cannot update a Component (Home) while Rendering a Different Component (Colapse). To locate the bad setState() call Inside Colapse, follow the stack trace as described in https://fb.me/setstate-in-render

Please help me, I need it before Monday.

  • Try to pass the function this way in onClick: onClick={()=>callbackParent(board.id)}

  • worked out, thank you very much

  • @Eduardohenrique Put as an answer detailing the reason why it has to be this way

1 answer

2

Is that passing the function this way onClick={callbackParent(board.id)} already with the parentheses (and the parameters when there are), the function is executed immediately in the rendering.

Now passing your function as a return from an Arrow Function onClick={() => callbackParent(board.id)}, then it will only be actually executed in the onClick event.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.