user3033194
user3033194

Reputation: 1831

Table not rendering properly inside <div> tag in React

I am new to React. I want to load some data in a table when it is available, else show 'Loading'. My render() function is currently as shown below:

return (
    <div>
        { this.state.loaded ? <tbody>{tuples}</tbody> : 'Loading ...' }
    </div>
);

My problem is, without the <div> tags, I get a build error from Gulp, but with them, my table columns are not staying aligned with the data.

Any idea how I can fix this?

Upvotes: 1

Views: 275

Answers (2)

Chris
Chris

Reputation: 59531

You could do the following:

return (this.state.loaded ? <tbody>{tuples}</tbody> : <span>Loading ...</span>);

The error you were getting was probably something like:

Uncaught Error: Invariant Violation: App.render(): A valid ReactComponent must be returned. You may have returned undefined, an array or some other invalid object.

Basically, React wants your render() function to return a valid ReactComponent. Without your wrapping <div> you would've returned a string when this.state.loaded is false, but strings are not the same as ReactComponent, hence the error.

In the solution provided above, we are returning the <tbody> element if the state.loaded is true (as you did as well). However, if it's false we return the "Loading ..." string wrapped inside of a <span>, which is a valid ReactComponent.

Obviously, you could choose any other element other than <span> if you'd prefer that, but I do suggest using it in most cases since, by default, it doesn't bring any visual changes - which is convenient is scenarios such as this one.

Upvotes: 1

Ashisha Nautiyal
Ashisha Nautiyal

Reputation: 1397

you can use the following:

return (

    <tbody>
            { this.state.loaded ? {tuples} : 'Loading ...' }
    </tbody>
    );

This will avoid the div element

Upvotes: 0

Related Questions