Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

luther wardle
seal-mask
.a{fill-rule:evenodd;}techdegree
luther wardle
Full Stack JavaScript Techdegree Student 18,029 Points

Horizontally aligning CSS flex-items in React?

Hi Everyone, I have a general question about using CSS in React I was hoping to get some clarification on. I'm not sure how to make my React components flex items so that they can display horizontally. I know that:

ReactDOM.render(<App />, document.getElementById('root')); is only rendering my <App/> element which contains all my other components. My goal is to display these components wrapped horizontally as flex items in their container. so that I can display them side by side. Could someone theoretically explain how this works to me?

any advice is much appreciated thanks!

3 Answers

Based on your code snippet, I think the reason is because you've wrapped all your <Header/>, <Subheader/> etc elements in a container div, so actually that one <div> is the only element that is a flex item on the #root container (Flexbox only affects the immediate children of the flex container, not children of children). So either remove that container div and see if the original CSS starts working, OR leave your App() function as-is but change the CSS to:

#root > div {
  display: flex;
}
#root > div > * {
  flex: 1;
}

and see if that solves it.

Hey Luther, If I understand your question right, you want any elements that are immediate children of your app's #root element to be flex-items that sit side-by-side in a horizontal, non-wrapping row? If that's right, it should just be simple CSS, no JavaScript- or React-specific consideration needed:

#root {
  display: flex;
  /* this is default so you don't even need to write it: flex-direction: row; */
}
#root > * {
  flex: 1; /* this allows the flex-items to grow to fill the space */
}
luther wardle
seal-mask
.a{fill-rule:evenodd;}techdegree
luther wardle
Full Stack JavaScript Techdegree Student 18,029 Points

Thanks Eric! I understand the method you are using but when I use #root > * it renders as if there are no children at all just the one component. here is my js.

function App(){
  return(
    <div>
    <Header/>
    <SubHeader/>
    <NameBox/>
    <PhoneNumberBox/>
    <EmailBox/>
    <CheckoutDateBox/>
    <ExpectedReturnBox/>
    </div>
  );
}