Reactjs Call Parent Method

ReactJS call parent method

2019 Update with react 16+ and ES6

Posting this since React.createClass is deprecated from react version 16 and the new Javascript ES6 will give you more benefits.

Parent

import React, {Component} from 'react';
import Child from './Child';

export default class Parent extends Component {

es6Function = (value) => {
console.log(value)
}

simplifiedFunction (value) {
console.log(value)
}

render () {
return (
<div>
<Child
es6Function = {this.es6Function}
simplifiedFunction = {this.simplifiedFunction}
/>
</div>
)
}

}

Child

import React, {Component} from 'react';

export default class Child extends Component {

render () {
return (
<div>
<h1 onClick= { () =>
this.props.simplifiedFunction(<SomethingThatYouWantToPassIn>)
}
> Something</h1>
</div>
)
}
}

Simplified stateless child as ES6 constant

import React from 'react';

const Child = (props) => {
return (
<div>
<h1 onClick= { () =>
props.es6Function(<SomethingThatYouWantToPassIn>)
}
> Something</h1>
</div>
)

}
export default Child;

How can I call a Parent function from a React functional component?

I'm not sure I understand the question correctly but you can call a function from the parent component inside the child easily like so:

export function Child({ func }) {
useEffect(() => {
console.log('Calling func');
func();
}, [func]);

return <div>I am the child component</div>;
}

export function Parent() {
const childFunc = () => console.log('call me!');

return (
<main>
<h1>Hello world</h1>

<Child func={childFunc} />
</main>
);
}

How can I call parent method in a child React component?

Try this. Passing the function down as props to the child component.

import Parent from './parent.js';
class Child extends React.Component {
constructor(props) {
super(props);
};

click = () => {
this.props.parentMethod();
}

render() {
<div onClick={this.click}>Hello Child</div>
}
}

class Parent extends React.Component {
constructor(props) {
super(props);
};

someMethod() {
console.log('bar');
}

render() {
<Child parentMethod={this.someMethod}>Hello Parent, {this.props.children}</Child>
}
}

How can I call parent function in a child React component?

I believe your error is because the OnClick event send 1 parameters to the function wich is the event. In your case the function deleteTask is receiving the event as params wich you name "props". You could fix this by using this syntax :

onClick={() => deleteTask()}

Or just removing the params props from your function declaration since you don't look like your using the event anyway.

function deleteTask(){ ...

React - call parent method in child component after passing it

You have to clone the children in order to do it.

export default GGModal = ({buttonLabel, children}) => {
const parentFunction => 'parent function';
<Modal
isOpen={modalIsOpen}
onRequestClose={closeModal}
style={{
overlay: { zIndex: 2 },
}}
>
{React.cloneElement(children, { parentFuntion })}
</Modal>
}

<GGModal buttonLabel='Login' /> <LoginScreen
setToken={setToken}
token={token}
setEmail={setEmail}
email={email}
/> </GGModal>

How to call a Parent method in Child Component using Hook (ForwardRef concept)

The reason you're getting the error is because refs in function components need to be passed using ref={buttonRef}, not ref="buttonRef". Class components have a thing they can do with string refs, but it's not recommended even there.

As for calling a function from a parent component, you don't need refs to do this. So if that was the only reason you were using a ref, you can remove the ref. Instead, pass the function as a prop:

const ParentComponent = (props) => {
const focusHandler = () => {
alert("hi");
}

return (
<div>
<ChildComponent focusHandler={focusHandler} />
</div>
)
}

const ChildComponent = (props) => {
return (
<div>
<button onClick={props.focusHandler}>Focus Input</button>
</div>
)
}

Call parent method in child component React

Child should be:

import React from 'react';
import axios from 'axios';

const AjaxForm = (props) => {

const handleSubmit=(e)=>{
axios.post(props.api, new FormData(e.target))
.then(function (response) {
console.log(response.data) //Api Response=> {message:'Thank you for your comment',callBack:'AddCommentDone'}
props.onSuccess(response.data)
});
}
return (
<form onSubmit={handleSubmit}>
{props.children}
<button type='submit'>Submit</button>
</form>
)
}

export default AjaxForm

Parent:

import React from 'react';
import AjaxForm from './../AjaxForm'

const Add = () => {

const AddCommentDone=(data)=>{
console.log('Done', data)
}

const AddCommentFail=()=>{
console.log('Failed')
}

return (
<AjaxForm api='/api/Comment/Add' onSuccess={AddCommentDone}>
<input name='Comment' placeholder='Text' type='text'></input>
</AjaxForm>
)
}

export default Add

How to call the parent Method in child class component in react

On Child class your component NavButton has an onClick attribute that calls onSetActive, so you can call investmentHandler on the onSetActive function:

//child component
import React, { Component } from "react";
const NavButton = ({ active, title, href, onSetActive }) => {
return (
<button
className={
active
? "btn btn-light regular-btn active"
: "btn btn-light regular-btn"
}
href={href}
onClick={onSetActive}
>
{title}
</button>
);
};
class Child extends Component {
constructor(props) {
super(props);
this.state = {
activeIndex: 1,
buttons: [
{
title: "1",
key: 0,
value: 1,
},
{
title: "3",
key: 1,
value: 3,
},
],
};
}
//It was changing active index
handleChangeActive(newActiveIndex) {
// console.log("Working");
this.setState({ activeIndex: newActiveIndex });
this.props.investmentHandler();
}

render() {
const { activeIndex } = this.state;
return (
<div>
<nav id="navbarMain">
<div className="navbar-nav flex-row">
{this.state.buttons.map((button, buttonIndex) => (
/* determine which nav button is active depending on the activeIndex state */
<NavButton
value={button.value}
onSetActive={() => this.handleChangeActive(buttonIndex)}
active={buttonIndex === activeIndex}
title={button.title}
key={button.key}
/>
))}
</div>
</nav>
</div>
);
}
}

export default Child;

On the Parent class when getting the props from the Child class you was calling "this.add" when you should be calling "this.Add":

// parent component
import React, { Component } from 'react'
import Child from './Child';
class Parent extends Component {
constructor(props) {
super(props)

this.state = {
firstValue: 1,
secondValue: 3,
result: ''
}

// this.add = this.add.bind(this);
}
//calculating the input values
Add = () => {
console.log('Im here')
var { firstValue, secondValue, result } = this.state;

result = firstValue + secondValue;
console.log(result);
document.getElementById("result").innerHTML = result;
}
render() {
return (
<>
<Child investmentHandler={this.Add} />
<p id="result">Result</p>
</>

)
}
}
export default Parent

I made this few changes and the code worked for me.

Call child method from parent

First off, let me express that this is generally not the way to go about things in React land. Usually what you want to do is pass down functionality to children in props, and pass up notifications from children in events (or better yet: dispatch).

But if you must expose an imperative method on a child component, you can use refs. Remember this is an escape hatch and usually indicates a better design is available.

Previously, refs were only supported for Class-based components.
With the advent of React Hooks, that's no longer the case

Modern React with Hooks (v16.8+)

const { forwardRef, useRef, useImperativeHandle } = React;

// We need to wrap component in `forwardRef` in order to gain
// access to the ref object that is assigned using the `ref` prop.
// This ref is passed as the second parameter to the function component.
const Child = forwardRef((props, ref) => {

// The component instance will be extended
// with whatever you return from the callback passed
// as the second argument
useImperativeHandle(ref, () => ({

getAlert() {
alert("getAlert from Child");
}

}));

return <h1>Hi</h1>;
});

const Parent = () => {
// In order to gain access to the child component instance,
// you need to assign it to a `ref`, so we call `useRef()` to get one
const childRef = useRef();

return (
<div>
<Child ref={childRef} />
<button onClick={() => childRef.current.getAlert()}>Click</button>
</div>
);
};

ReactDOM.render(
<Parent />,
document.getElementById('root')
);
<script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>

<div id="root"></div>


Related Topics



Leave a reply



Submit