4

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.

2
  • just return the two tr in a string instead of array? Commented Oct 20, 2015 at 10:02
  • Actually real life task is a bit more complex. So, string would not be enough Commented Oct 20, 2015 at 10:04

1 Answer 1

17

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>
    );
}
Sign up to request clarification or add additional context in comments.

1 Comment

I had no idea you could have multiple tbody tags. Good to know.

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.