0

I need to render <tr> start and close it, based on a condition:

{grid.map((item, index) => {
    return <React.Fragment key={index}>
        {item.x === 0 ? <tr/> : ""}
        <td id={`td_${item.x}_${item.y}`}>
            {item.name}
        </td>
    </React.Fragment>
})}

Above code rendering all <td> tag outside of <tr> tag, but I want all <td> in <tr> tag. In this code, I want <tr> start when item.x === 0 and need to render </tr> end in bottom this loop.

{grid.map((item, index) => {
    return <React.Fragment key={index}>
        {item.x === 0 ? <tr> : ""}
        <td id={`td_${item.x}_${item.y}`}>
            {item.name}
        </td>
        {item.x === 0 ? </tr> : ""}
    </React.Fragment>
})}

This code showing error in jsx syntax error.

1
  • Could you show us data you keep in grid array? Commented Jul 28, 2020 at 13:14

1 Answer 1

1

React component trees aren't HTML strings, they're object trees. You need to have a tr object, provide it with a bunch of td children, and then switch to a new tr object and provide its children to it.

Ideally, change how you're storing grid so that it contains the rows, with child objects/arrays for the cells.

If you can't do that, you can do it on the fly:

const rows = [];
let children = [];
for (const item of grid) {
    if (grid.x === 0 && children.length) {
        rows.push(children);
        children = [];
    }
    children.push(item);
}
if (children.length) {
    rows.push(children);
}

Then to render:

{rows.map((children, index) => (
    <tr key={index}>
        {children.map(item =>
            <td id={`td_${item.x}_${item.y}`}>
                {item.name}
             </td>
        )}
    </tr>
))}

You'll want to double-check that for minor typos, etc., but it's the fundamental idea: Build an array of rows, with arrays of cells inside.

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

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.