Confused about CSS Grid in React

Hello! I’m building a React app and I want to use CSS grid to format a parent component. However, I’ve noticed that when applying CSS, it only works when I directly style a component’s inner html rather than the component as a whole. Here’s an example so you understand what I mean:

This doesn’t work:

//ParentGridComponent.js
/*imports up here*/

export default function ParentGridComponent(){

return(
<div>
<ParentGridComponent id='grid'>
    <ChildGridItemComponentOne id='item-one'/>
     <ChildGridItemComponentTwo id='item-two'/>
     <ChildGridItemComponentThree id='item-three'/>
</ParentGridComponent>
</div>
)
}

w/ this file:

//ParentGridComponent.css

#grid {
display: grid;
grid-template-rows: 1fr 1fr;
grid-template-columns: 1fr 1fr;
}

#item-one {
/*some css here*/
}

/*etc.*/

But this does work:

export default function ParentGridComponent(){
return (
<div id='grid'>
<ParentGridComponent>
    <div id='item-one'></div>
     <div id='item-two'></div>
     <div id='item-three'></div>
</ParentGridComponent>
</div>)

}

Is there a way to have child components themselves act like grid items, or is it necessary to do as above in order for it to work? Am I misunderstanding something?

Thank you so much!

Idea: Do I just wrap every child component in a div and give it its corresponding id/className?

Did you try it with ClassName instead of Id ??

Yes. It makes no difference. I think I’ve figured it out though.

Share your knowledge if you’ve figured it out.

See above.
I either wrap the component in a div and style the div, or decide that it doesn’t need to be a React component at all and just make it a div within the parent. Does that make sense?

Yes one important thing here is that div is a wrapper in itself. So anything you wrap within it will be considered.

I haven’t worked with React in a while, so maybe I’m off base. But my guess would be that unless you handle the id you’re passing as a prop in the child component, then that’s just going to get thrown away and unused.

<ChildGridItemComponentOne id='item-one'/>
function ChildGridItemComponentOne({ id }) {
  return <div id={id}></div>
}

Maybe you can generate a style object and pass it to child components as a property. e.g.

Within the parent component:
const GridStyle = { display: flex }

Within the child component:

Hello, World!

Besides, I am confused with the way how you construct parent and children components. Why you put ParentGridComponent component inside its own definition?

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.