How to pass a function to another component through props?

Asked

Viewed 5,865 times

2

I’m trying to do a todolist with React and at the moment I have two components: Todolistapp and Todoform. In Todolistapp I have a function that adds a value in a list that is in the state, but this value comes from another component: Todoform.

inserir a descrição da imagem aqui

I’ll put the code of both:

import React from 'react';
import TodoForm from '../components/TodoForm';

export default class TodoListApp extends React.Component {

  constructor(props) {
    super(props);

    this.state = {
      items: []
    }
  }

  render() {
    return (
      <TodoForm pushToItems={this.pushToItems}></TodoForm>
    );
  }


 //Tento passar esta função para o outro componente
  pushToItems = (todo) => {
    this.setState({
      items: [...this.state.items, todo]
    });
  }
}

Presentation component:

import React from 'react';

export default class TodoForm extends React.Component {

  constructor(props) {
    super(props);

    this.state = {
      todo: ''
    }
  }

  handleChange = (event) => {
    this.setState({
      [event.target.name]: event.target.value,
    });
  }

  //Chamo a função que vem do outro componente através das props.
  onAdd = () => {
    this.props.pushToItems(this.state.todo);
  }

  render() {
    return (
      <div>
        <input type="text" name="todo" placeholder="Enter todo here"
         onChange={this.handleChange}></input>
        <button type="button" onClick={this.onAdd}>Add</button>
      </div>
    );
  }

}

What’s happening is that when I click on the add a whole button, it returns to me:

Uncaught Typeerror: this.props.pushToItems is not a Function

As if the todoform component is not receiving the function as prop.

Does anyone know what it can be?

  • I couldn’t reproduce the problem. I created a Codesandbox, but it’s working...

  • @Luizfelipe And here it continues.... https://prnt.sc/obggs6

3 answers

1

This problem occurs because the context is broken, you can read more here. Briefly, ALWAYS use bind in the manufacturer for all its functions:

 constructor(props) {
   super(props);

   this.handleChange = this.handleChange.bind(this);

   this.state = {
     todo: ''
   }
 }

That’s a drag. Fortunately, Hooks eliminates this - and many others - problem by not using classes.

0

When passing the function as props to another component, try to do this way:

  <TodoForm pushToItems={this.pushToItems.bind(this)}></TodoForm>

0

https://pt-br.reactjs.org/docs/faq-functions.html

You can on the child use :

this.props.NomeDaFunc(Parametro1)

In the father you use:

<SeuComponente NomedaFunc={ this.NomeDaFunc.bind(this) } />

It will run her normally, this is something interesting if you want to change a father’s state from within a daughter, as well as using Func. validation from within it.

Browser other questions tagged

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