'Objects are not valid as a React child -> Build time error -> next js typescript

Return object from function in build time error ... when I build my app(npm run build). show me this error

->Objects are not valid as a React child (found: object with keys {name, age}). If you meant to render a collection of children, use an array instead.

That is my code

const obj = {
    name:"A",
    age:20
}
function ObjFileReturn():[obj:{name:string,age:number}] {
  return [obj];
}
export default ObjFileReturn;

The question is -> How can I return obj from a function using ts

please help me and ignore my writing style.



Solution 1:[1]

If you are trying to return the object as a component you need to first stringify the object or transform it from an object type. Objects are not valid JSX/React elements.

You can do:

type objType = {
  name: string
  age: number
}

const obj: objType = {
    name: "A",
    age: 20
}

function ObjFileReturn() {
  return <div>{JSON.stringify(obj, null, '\t'}</div>

export default ObjFileReturn;

JSON.stringify() converts the object to string which you can use inside a div to return from the functional comonent. The extra parameters in strigify pretty-print it so that it remains formatted.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

Hope that helps!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tom