2

Consider the following piece of code

class App extends React.Component<{}, IState> {
 public state: IState = {
  todos: TODOS
 }

 private onItemRemove = (item: any) {
  /////
 }

   render() {
    return (
      <div>
        <ToDoList
          todos={this.state.todos}
          onItemRemove={() => this.onItemRemove}
        />
      </div>
    );
  } 
}

const ToDoList: React.SFC<IProps> = props => {
  return (
    <ul>
      {props.todos.map((todo: any) => {
        return (
          <ToDoItem
            name={todo.name}
            key={todo.id}
            id={todo.id.toString()}
            onItemRemove={props.onItemRemove}
          />
        );
      })}
    </ul>
  );
}

const ToDoItem: React.SFC<IProps> = props => {
  return (
    <li>
      {props.name}
      <button onClick={() => props.onItemRemove(props.id)}>
        Remove
      </button>
    </li>
  );
};

I've heard that this can be achieved with the help of either redux or context, but is it possible to pass down from App to ToDoItem the onItemRemove method without using either redux or context ?

Or maybe there is a more optimal way of achieving this which I might be missing ?

1 Answers1

4

From the official docs: Don’t use context just to avoid passing props a few levels down. Stick to cases where the same data needs to be accessed in many components at multiple levels. https://reactjs.org/docs/context.html#when-to-use-context

So your code seems pretty optimal.

Ali Ankarali
  • 2,761
  • 3
  • 18
  • 30