0

I am trying to render a table inside a react component but having trouble aligning the rows with the header

render() {
         console.log("Top Searches",this.props.topSearches)
         return(
          <div className="topsearches">
          <table border="2" align="center">
          <th> Search Term </th>
          <th>Count </th>
             {this.props.topSearches.map((top_search, index) => (
                  <tr>
                    {Object.keys(top_search).map(function(key) {
                      return <div>      
                      <tbody>
                      <td align="center">{key} </td>
                      <td align="right">{top_search[key]}</td>
                      </tbody>
                       </div>

                      })}


                </tr>
            ))}
            </table>
          </div>

      )
    }

This is the output i am getting

1 Answer 1

1

enter image description here

I assume, you are trying to achieve something like this.

I have edited this in codesandbox here. https://codesandbox.io/s/sparkling-sound-yd1ih

return (
    <div className="topsearches">
      <table border="2" align="center">
        <thead>
          <th> Search Term </th>
          <th>Count </th>
        </thead>
        <tbody>
          {props.topSearches.map((top_search, index) =>
            Object.keys(top_search).map((key, index) => {
              return (
                <tr>
                  <td>{key}</td>
                  <td>{top_search[key]}</td>
                </tr>
              );
            })
          )}
        </tbody>
      </table>
    </div>
  );

Modification I made to achieve this:

  • Added <thead>
  • Corrected <tbody> loop

Please let me know if you have any further questions!

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

8 Comments

One issie I have is my json has only one object so
so [{"apple": 42, iphone:10} instead of [ {apple:42}, {iphone:10}]
So will it display only one value in a row ? Do you want to display only one value in a row ?
yes i want it displaye dthe way u have it but having difficulty ding that
please provide your JSON input data
|

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.