How do I get a function within a functional component to pick up the props of that component?

Asked

Viewed 71 times

1

I’m starting the study in React and am like a difficulty in this component, I want to pass the props that the component Todo receives to the handleAdd function, being that at the moment this this within the function is returning undenifed. The code is as follows::

import React from 'react';
import PageHeader from '../template/PageHeader';
import Forms from '../componentes/Forms';
import List from '../componentes/List';

const Todo = (props) => {
  const handleAdd = (props) => {
    console.log(this);
  };

  return (
    <div>
      <PageHeader name='Tarefas ' small='Cadastro'></PageHeader>
      <Forms handleAdd={handleAdd}></Forms>
      <List></List>
    </div>
  );
};
export default Todo;

1 answer

5


If you want to access the props of a component within a function defined within it (such as handleAdd), you don’t need to use this or even pass them as argument. You can access them normally, using the scope of Javascript, which allows you to access variables of the upper scope.

Thus:

import React from 'react';
import PageHeader from '../template/PageHeader';
import Forms from '../componentes/Forms';
import List from '../componentes/List';

function Todo(props) {
  function handleAdd() {
    console.log(props);
  }

  return (
    <div>
      <PageHeader name='Tarefas ' small='Cadastro'></PageHeader>
      <Forms handleAdd={handleAdd}></Forms>
      <List></List>
    </div>
  );
};

export default Todo;

See a similar example working:

function Form(props) {
  return (
    <button onClick={props.onClick}>Clique-me!</button>
  );
}

function Todo(props) {
  function handleClick() {
    console.log(props);
  }

  return (
    <div>
      <span>{props.todo}</span> &nbsp;
      <Form onClick={handleClick} />
    </div>
  );
}

ReactDOM.render(
  <React.Fragment>
    <Todo todo="Foo" />
    <Todo todo="Bar" />
    <Todo todo="Baz" />
  </React.Fragment>,
  document.querySelector('#app')
);
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

<div id="app"></div>

Note also that I modified the Arrow functions by normal function statements, as there is no reason to use Arrow functions in that case. :)

  • In case I wanted when Handle pointed to this pointed to the props that Todo gets, like a bind in a class

  • Just use props, since handleAdd is within the scope of the component Todo. Did you test it? Did you make a mistake? It seems to me it’s all right. I edited the answer to add a functional example. :)

  • 2

    Thank you for your help and clarification :D

Browser other questions tagged

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