Home > database >  React not rendering the array
React not rendering the array

Time:08-08

I am new to react and trying to create a simple todo list to understand React states and props but cant seem to understand why its not rendering the array on the screen. When the button is pressed it console logs the array of the inputs so I know that works.

here is each component currently there are no errors just nothing shows up.

App.js:

import React from "react";
import ControlPanel from "./ControlPanel";
import TodoList from "./TodoList";

class App extends React.Component {
  state = { TodoList: [] };

  addTask = (todoItem) => {
    this.setState({ TodoList: [...this.state.TodoList, todoItem] });
    console.log(this.state.TodoList);
  };

  render() {
    return (
      <div>
        <ControlPanel addTask={this.addTask} />
        <TodoList todoitem={this.state.TodoList} />
      </div>
    );
  }
}

export default App;

ControlPanel.js:

import React from "react";

class ControlPanel extends React.Component {
  state = { todoItem: "" };

  addItem = (event) => {
    event.preventDefault();

    this.props.addTask(this.state.todoItem);
  };

  render() {
    return (
      <div className="ui card">
        <div className="ui input">
          <input
            onChange={(e) => {
              this.setState({ todoItem: e.target.value });
            }}
            value={this.state.todoItem}
            type="text"
            placeholder="Todo List Item"
          />
        </div>
        <div>
          <button onClick={this.addItem} className="ui button">
            Add Item
          </button>
        </div>
      </div>
    );
  }
}

export default ControlPanel;

TodoList.js:

import React from "react";
import TodoItem from "./TodoItem";

const TodoList = (props) => {
  const todoItems = props.TodoList?.map((todo) => {
    return <TodoItem TodoItem={TodoItem} />;
  });

  return <div>{todoItems}</div>;
};

export default TodoList;

TodoItem.js

import React from "react";

const TodoItem = (props) => {
  return <div>{this.props.TodoItem}</div>;
};

export default TodoItem;

CodePudding user response:

import React from "react";
import TodoItem from "./TodoItem";

const TodoList = (props) => {
  const todoItems = props.TodoList?.map((todo,idx) => {
    return <TodoItem TodoItem={todo} key={idx} />; // idx or any unique key
  });

  return <div>{todoItems}</div>;
};

export default TodoList;

More information for key https://reactjs.org/docs/lists-and-keys.html

  • Related