4c65736975
4c65736975

Reputation: 119

How to call component function from parent component and change it state to render child component in React

I have problem with passing state from parent component. I'm trying to call function in my ParentComponent in onClick from my ChildComponent to render ChildComponent in ParentComponent. I'm new in React Library and I'm really don't know how I can achive this. I've tried something like that.

ParentComponent:

import React from 'react'
import {ChildComponent, showDialog} from './childComponent'

const ParentComponent = () => {
    return (
        <div>
            <button type='button' onClick={() => showDialog()}>
        </div>
    )
}

export default ParentComponent

ChildComponent:

import {React, useState} from 'react'

const {isOpened, setIsOpened} = useState(false)

function showDialog() {
    setIsOpened(true)
}

function ChildComponent() {
    if (isOpened) {
        return (
            <dialog open></dialog>
        )
    }
}

export {ChildComponent, showDialog}

Upvotes: 0

Views: 55

Answers (1)

Sean Dillon
Sean Dillon

Reputation: 250

You should be passing the activation function as a prop to the child component. Then using the function on click in the child.

Upvotes: 0

Related Questions