Home > Software engineering >  React JS - how to read specific attribute from a child JSX before mounting it to the DOM
React JS - how to read specific attribute from a child JSX before mounting it to the DOM

Time:08-08

What I need to achieve is to handle a specific attribute from one JSX component that I import to its parent component in a way that I will display here.

Child component returns JSX with 'someId' attribute:

return <h1 someId={123}>{title}</h1>

And the parent assigns this JSX to a variable and then needs to read this 'someId' attribute from it - before mounting the variable to the DOM:

let mySpecialChild = <Child title="Hello boys and girls!" />
let mySpecialChildId = mySpecialChild.someId

mySpecialChild.someId is now empty. I know it looks strange and against ReactJS rules but I need this for a very specific use case (in a loop, with additional conditions related to this child attribute). Here I created a sandbox for tests:

enter image description here

  • Related