简体   繁体   中英

Align conditional rendered component on same line - Material UI

I have a component that is re-used twice and the result is:

|MyComponent1|
|MyComponent2|

My condition is:

if (a == 'One' || b == 'Two'){
 <MyComponent data={data}/>
}

The a & b condition is satisfied after each iteration with different data (hence "MyComponent1" and "MyComponent2"), hence the component gets rendered twice. I'm using material UI and pretty new to it. I tried using Grid but did not work. I want the same component with different values to be on the same line like:

|MyComponent2||MyComponent1|

Anything that can be used with Material-UI?

I don't know if you mean on the same line as in the css. But if you want each component to be rendered conditionally you'll want it like this. This example uses the ternary operator syntax. It's the same as saying

if(condition){ do this }else{ doing this instead }

{a === 'One' ? <MyComponent data={data}/> : null}
{b === 'Two' ? <MyComponent data={data}/> : null}


<Grid direction="row" >
    {a === 'One' ? <MyComponent data={data}/> : null}
    {b === 'Two' ? <MyComponent data={data}/> : null}
</Grid>

That should put them in a grid. You might have css or styling causing issues though.

You can do it in this ways. Using null is not a good practice

  1. (a === 'One' || b === 'Two')&&(<MyComponent data={data}/>)
  2. (a ==='One' || b === 'Two')?(<MyComponent data={data}/>):<></>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM