0

export default class App extends React.Component {
  constructor() {
    super();
    this.state = {
      todos: 5
    };
  }

  handleClick = () => {
    this.setState({ todos: this.state.todos + 1 });
  };

  render() {
    return (
      <div className="App">
        <h1>ToDo List</h1>
        <p>Just keep giving me things to do</p>
        <p>I still have {this.state.todos} things to do</p>
        <AddTodo todos={this.state.todos} handleClick={this.handleClick} />
      </div>
    );
  }
}

I am trying to update <p>I still have {this.state.todos} things to do</p> in the Parent to increase by 1 for every button click in the Child Component. What am I missing? I am not getting any errors but it is not functional.

import React from "react";

export default function AddTodo(handleClick) {
  return (
    <div className="AddTodo">
      <button onClick={() => handleClick}>Add Another</button>
    </div>
  );
}
Thomas M
  • 13
  • 5
  • Does this answer your question? [How to update parent's state in React?](https://stackoverflow.com/questions/35537229/how-to-update-parents-state-in-react) – Kevin.a Jan 05 '21 at 19:55

1 Answers1

0

Props is the first value passed to a functional component, it's an object and you would need to destructure handleClick from it.

export default function AddTodo({ handleClick }) {
  return (
    <div className="AddTodo">
      <button onClick={handleClick}>Add Another</button>
    </div>
  );
}

Also change your handle click function to this

handleClick = () => {
    this.setState(({ todos }) => ({ todos: todos + 1 }));
  };

a working example

const AddTodo = ({ onClick }) => (
  <div className="AddTodo">
    <button onClick={onClick}>Add Another</button>
  </div>
);

const App = () => {
  const [todos, setTodos] = React.useState(5);

  const onClick = () => {
    setTodos((oldTodos) => oldTodos + 1);
  };

  return (
    <div className="App">
      <h1>ToDo List</h1>
      <p>Just keep giving me things to do</p>
      <p>I still have {todos} things to do</p>
      <AddTodo todos={todos} onClick={onClick} />
    </div>
  );
}

ReactDOM.render(<App />, document.getElementById('root'))
<script src="https://unpkg.com/react@17/umd/react.production.min.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js" crossorigin></script>
<div id="root"></div>
Julian Kleine
  • 1,539
  • 6
  • 14