Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Render 2 table rows in ReactJS

I want to achieve expandable row functionality for table. Let's assume we have table with task names and task complexity. When you click on one task the description of task is shown below. I try to do it this way with ReactJS (in render method):

  if (selectedTask === task.id) {
    return [
      <tr>
        <td>{task.name}</td>
        <td>{task.complexity}</td>
      </tr>,
      <tr>
        <td colSpan="2">{task.description}</td>
      </tr>
    ];
  } else {
    return <tr>
      <td>{task.name}</td>
      <td>{task.complexity}</td>
    </tr>;
  }

And it doesn't work. It says: A valid ReactComponent must be returned. You may have returned undefined, an array or some other invalid object I tried also to wrap 2 rows in a div but I get wrong rendering. Please, suggest correct solution.

like image 503
gs_vlad Avatar asked Dec 02 '22 16:12

gs_vlad


1 Answers

The render() method on a React component must always return a single element. No exceptions.

In your case, I would suggest wrapping everything inside a tbody element. You can have as many of those as you want in a table without disrupting your row structure, and then you'll always return one element inside render().

if (selectedTask === task.id) {
    return (
        <tbody>
            <tr>
                <td>{task.name}</td>
                <td>{task.complexity}</td>
            </tr>,
            <tr>
                <td colSpan="2">{task.description}</td>
            </tr>
       </tbody>
    );
} else {
    return (
        <tbody>
            <tr>
                <td>{task.name}</td>
                <td>{task.complexity}</td>
            </tr>
      </tbody>
    );
}
like image 64
Andy Noelker Avatar answered Dec 06 '22 10:12

Andy Noelker