nextjs call function from parent component

nextjs

In a Next.js app, you can call a function from a parent component by passing the function as a prop to the child component. Here’s an example:

import React from 'react'

// Parent component
function Parent() {
    function handleClick() {
        console.log('Button clicked')
    }

    return (
        <Child handleClick={handleClick}/>
    )
}

// Child component
function Child(props) {
    return (
        <button onClick={props.handleClick}>Click me</button>
    )
}

In this example, the handleClick function is defined in the Parent component and passed to the Child component as a prop. When the button in the Child component is clicked, the handleClick function will be called.

You can also use this approach to pass data from the parent component to the child component. For example:

import React from 'react'

// Parent component
function Parent() {
    const data = {name: 'John', age: 30}

    return (
        <Child data={data}/>
    )
}

// Child component
function Child(props) {
    return (
        <div>
            Name: {props.data.name}
            Age: {props.data.age}
        </div>
    )
}

In this example, the data object is passed from the Parent component to the Child component as a prop. The Child component can then access the data by using props.data.