fesieg
fesieg

Reputation: 478

Problem when storing JSX elements inside useState Array of Objects

I am trying to change a React component so that I can eventually sort its contents. To that end, I extracted most of the render method into an array of objects, such as

const [items, setItems] = useState([        
        {id : 1, item: <div id="SelectionEntryBuildNr">{buildNr}</div> },
        {id : 2, item: <Timestamp id="SelectionEntryTimestamp" relative date={timestamp} /> }
]

the buildNr and timestamp variables are state as well

I then try to render the component

<div className={className} onClick={onClick}>
    {items.map(i => i.item)}
</div>

and it renders everything correclty, however, where it displayed the data before, it now doesn't seem to display any data (the relative date defaults to "just then"). It seems like it can't correctly access the data. When I log items, I get an Array that contains this:

0:
id: 0
item: {$$typeof: Symbol(react.element), type: "div", key: null, ref: null, props: {…}, …}
__proto__: Object

Why are the JSX elements stored like that? And why can't it access the state variables?

Upvotes: 2

Views: 2208

Answers (1)

lanxion
lanxion

Reputation: 1430

The reason why JSX is stored like that is because, at the end of the day, JSX is just syntactical sugar for react.createElement() syntax, which react will translate into the function with the right parameters to create the appropriate react element. check https://reactjs.org/docs/react-without-jsx.html#:~:text=JSX%20is%20not%20a%20requirement,%2C%20...children)%20 to understand this. So in essence, your JSX is being compiled into a react element and stored in that form. In your object that is returned, you can check what value is used for children to get a better idea of what is happening to the state variable that is being passed in.

As to understand why this may not be working, it is possible that it is compiling the JSX before state variables have been set, or perhaps it is just not possible to use state variables inside another state variable, or perhaps the variable cannot be found due to scoping issue. Most likely, undefined is being passed into the children of the element.

Upvotes: 3

Related Questions