0

Hi I want to have multiple TRs and inside one, have multiple TDs using react I want to loop through my comparedProperties object and create the table in render method dynamically but I get this error:

Uncaught Error: Objects are not valid as a React child (found: object with keys {id, address, long, lat, cityId, cityDistrict, phone, name, userId, city}). If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons. Check the render method of Comparison.

my data object is like this and I can not change its structure:

       //this is a samle data, keys in this object can dynamically change elsewhere
       let comparedProperties = {
         id: [1001,1002],
         address: ["abc","def"],
       };

this is my code:

   class Comparison extends Component {

render() {
    let comparedProperties = {
        id: [1001, 1002],
        address: ["abc", "def"]
    };

    let comparedItemsData = [];

    for (var key in comparedProperties) {
        if (comparedProperties.hasOwnProperty(key)) {
            let newTR = <tr key={Math.random()} className="compare-table-row">
                <td className="table-item-header">
                    {key}
                </td>
                {comparedProperties[key].map((item) => {
                    return <td key={Math.random()} className="table-item">{item}</td>;
                })}
            </tr>;

            comparedItemsData.push(newTR)
        }
    }

    return (
        <table className="compare-table">
            <tbody>
            {comparedItemsData}
            </tbody>
        </table>
    )
}
     }

    const mapStateToProps = (state) => ({
          ...state
          });
           const mapDispatchToProps = (dispatch) => ({
              actions: bindActionCreators(Actions, dispatch)
          });
          export default connect(
                mapStateToProps,
               mapDispatchToProps
            )(Comparison);

update answer:

so I figuerd where the problem was but I expexted better error message from react the problem was that in my comparedProperties I had an object inside the array that caused the error

    let comparedProperties = {"id":[101,102],"estateAgency":[{"id":1},{"id":2}]}
1

2 Answers 2

1

Edit 50o29v2vok

Are you trying to do something like that ?

  render(){

    let comparedProperties = {
      id: [1001, 1002],
      address: ["abc", "def"],
    };

    return (
      <table>

        {Object.keys(comparedProperties).map(key=>(

          <tr key={Math.random()} className="compare-table-row">

            <td className="table-item-header">
              {key}
            </td>

            {comparedProperties[key].map((item) => (
              <td key={Math.random()} className="table-item">{item}</td>
            ))}

          </tr>

        ))}

      </table>
    )
  }

Or if you want to try as a a stateless comp you insert in your table :

const ComparedItemsData = ({ comparedProperties }) =>(
    <React.Fragment>
      {Object.keys(comparedProperties).map(key => (
        <tr key={Math.random()} className="compare-table-row">
          <td className="table-item-header">{key}</td>
          {comparedProperties[key].map(item => (
            <td key={Math.random()} className="table-item">
              {item}
            </td>
          ))}
        </tr>
      ))}
    </React.Fragment>
)

const App = ()=>{

  let comparedProperties = {
    id: [1001, 1002],
    address: ["abc", "def"]
  };

  return (
    <table className="compare-table">
      <tbody>
        <ComparedItemsData comparedProperties={comparedProperties}/>
      </tbody>
    </table>
  )
}
Sign up to request clarification or add additional context in comments.

8 Comments

thanks that looks promising but I get this error : Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in. Check the render method of ComparedItemsData.
It sounds like you did put ComparedItemsData in a separate file without exporting it to use it in your main file. Do you export your comp like this : export default ComparedItemsData at the bottom of the file?
please see my code again, I put some more in it, the thing is I dont know why your sandbox code works because I am basically doing the same thing
if I want to use this react.fragment where should I put it? I tested it inside this file and outside the scope of the class but got the error that I told in previous comment
Your last code is working well on sandbox, so the problem seems to be somewhere else... I just copy/paste your code and everything is working
|
0

You just need to return the td elements from within map function. Also never specify Math.random() as a key to the react elements because everytime render is called a new key will be assigned and it will force React to re-render the entire component even though nothing would have changed.

for (var key in comparedProperties) {
    if (comparedProperties.hasOwnProperty(key)) {
          let newTR = <tr key={key} className="compare-table-row">
                <td className="table-item-header">
                    {key}
                </td>

                //comparedProperties[key] is an array of
               // values that I want to make them as td elements
                { comparedProperties[key].map((item) => {
                    return <td  key={item} className="table-item">{item}</td>;
                })}
            </tr>;


            comparedItemsData.push(newTR)

        }
}

2 Comments

How are you rendering comparedItemsData. I think you could be rendering comparedProperties instead of comparedItemsData
no, it is like this: <table className="compare-table"> <tbody> {comparedItemsData} </tbody> </table>

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.