1

I have the following react component which creates a list of Tasks.

The code works ok this.props.data and when the data is empty, no Task appears.

I would like to change the code in a way so that if the array is empty a single text

"list empty"

is displayed instead.

I have tried to create a function for listItems and inside add some logic, but I cannot call it from JXS, example <div>{listItems()}</div> although I am not even sure if this is the correct approach.

Any ideas?

import React, { Component } from 'react';
import Task from './Task.js'

class TasksList extends Component {
   constructor(props) {
       super(props);
   }
   render() {
       const data = this.props.data;
       const listItems = data.map(todo => {
           return <Task
               id={todo.id}
               key={todo.id.toString()}
               title={todo.title}
               onTitleChange={this.props.onTitleChange}
               onTaskDelete={this.props.onTaskDelete}
           />
       });
       return (
           <div>{listItems}</div>
       )
   }
}

export default TasksList;

2 Answers 2

1

This should works:

const listItems = data.length == 0 ? "List empty" : data.map(todo => { ... });

Sign up to request clarification or add additional context in comments.

Comments

0

You can use something like below, hope this helps.

class TasksList extends Component {
   constructor(props) {
       super(props);
   }
   render() {

       if(this.props.data.length > 0) {
         return (<div>
           {data.map(todo => {
           return <Task
               id={todo.id}
               key={todo.id.toString()}
               title={todo.title}
               onTitleChange={this.props.onTitleChange}
               onTaskDelete={this.props.onTaskDelete}
           />
         });}
       </div>);
       }
       return (
           <div>list empty</div>
       )
   }
}

export default TasksList;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.