Alex
Alex

Reputation: 323

Material UI: best way to set elements side by side

I'm currently using Material UI to style an ecommerce project. I'm trying to figure out how to make all of the elements (Typography, Buttons) display side by side in a row instead of vertically.

Is there a way to do this simply with material UI? Should I add CSS? I previously tried adding each element to a Grid item within a Container, it kind of worked (couldn't center), but doesn't seem like the right approach for this scenario.

If you see my screenshot below, I'm trying to set "T-Shirt Twilight", the image, "$49.99", the quantity input buttons and "Remove" side by side horizontally.

Elements I'm trying to set side by side:

  <div className="App">
        {products.map((item, index) => (

          <Grid container item xs={12}>
            <Grid item xs={1} />
            <Grid item xs={10}>

                <Grid item xs={12} container key={item.id}>
                    <Grid item xs={1} />
                    <Grid item xs={10}>

                      <Typography>{item.title}</Typography>
                      <img src={require(`../images/${item.image}`)} className={classes.productImage}></img>
                      <Typography>${(item.quantity * item.price).toFixed(2)}</Typography>

                      <ButtonGroup size="small">
                        <Button type="button" onClick={item.quantity > 1 ? () => decreaseQuantity(index) : null}>-</Button>
                        <Button>{item.quantity}</Button>
                        <Button type="button" onClick={() => increaseQuantity(index)}>+</Button>
                      </ButtonGroup>

                      <Button
                        onClick={() => removeItem(index)}>
                      Remove
                      </Button>

                    </Grid>
                    <Grid item xs={1} />
                </Grid>

            </Grid>
            <Grid item xs={1} />
          </Grid>
        ))}
      </div>

Screenshot for reference: enter image description here

Full code:

import React, { useState, useEffect } from 'react';
import './../App.css';
import * as ReactBootStrap from 'react-bootstrap';
import {Link} from 'react-router-dom';
import { getQuantity, getTotal } from '../helpers/helperTools';
import {Grid, Typography,useMediaQuery, useTheme, Container, Button, ButtonGroup} from '@material-ui/core';
import {makeStyles} from '@material-ui/core/styles';

const useStyles = makeStyles((theme) => ({
    productImage: {
      maxWidth: '20%'
}
}))

function Cart({ setQty: setParentQty }) {
    const classes = useStyles();
    const [products, setProducts] = useState([]);

    function updateQty(products){
        /* var holder = 0;
        products.forEach((a, b) => {
          holder = holder + a.quantity
        })*/
        // setQty({quantity: holder})
        // localStorage.setItem('quantity', JSON.stringify({ quantity: newQty }))
        setParentQty({ quantity: getQuantity(products) });
      }

    useEffect(function() {
      const storageItems = JSON.parse(localStorage.getItem('product'));
      const products = storageItems || [];
      setProducts(products);
      updateQty(products);
    }, []);

    function decreaseQuantity(index) {
      if (products[index]){
        const newProducts = products.map((a, b) => {
          if (b === index) return {...a, quantity: a.quantity - 1}
          else return a
        });

        setProducts(newProducts);
        localStorage.setItem('product', JSON.stringify(newProducts))
        updateQty(newProducts)
      }
    }

    function increaseQuantity(index) {
        if (!products[index]) return;

        const newProducts = products.map((a, b) => {
          if (b === index) return {...a, quantity: a.quantity + 1}
          else return a
        })

        setProducts(newProducts)
        localStorage.setItem('product', JSON.stringify(newProducts))
        updateQty(newProducts);
    }

    function removeItem(index){
      const product = products[index];

      if (!product) return;

      const newProducts = products.filter((v, z) => z !== index);
      setProducts(newProducts);

      localStorage.setItem('product', JSON.stringify(newProducts));

      updateQty(newProducts);
    }

     if (products.length === 0) {
       return (
         <div className="App">
          <p>
            Cart Empty
          </p>
          <Link to={`/`}>
          <p>Continue shopping</p>
          </Link>
         </div>)
     }

    return (
      <div className="App">
        {products.map((item, index) => (

          <Grid container item xs={12}>
            <Grid item xs={1} />
            <Grid item xs={10}>

                <Grid item xs={12} container key={item.id}>
                    <Grid item xs={1} />
                    <Grid item xs={10}>

                      <Typography>{item.title}</Typography>
                      <img src={require(`../images/${item.image}`)} className={classes.productImage}></img>
                      <Typography>${(item.quantity * item.price).toFixed(2)}</Typography>

                      <ButtonGroup size="small">
                        <Button type="button" onClick={item.quantity > 1 ? () => decreaseQuantity(index) : null}>-</Button>
                        <Button>{item.quantity}</Button>
                        <Button type="button" onClick={() => increaseQuantity(index)}>+</Button>
                      </ButtonGroup>

                      <Button
                        onClick={() => removeItem(index)}>
                      Remove
                      </Button>

                    </Grid>
                    <Grid item xs={1} />
                </Grid>

            </Grid>
            <Grid item xs={1} />
          </Grid>
        ))}
      </div>

    );
}

export default Cart;

Upvotes: 5

Views: 12675

Answers (1)

Vo Quoc Thang
Vo Quoc Thang

Reputation: 1396

Just use inline style for it. I also removed some unnecessary grid items. May be you want to grid more about breakpoints in Grid. Working CodeSandBox

    <Grid container>
          <Grid item xs={1} />
          <Grid item xs={10} style={{ display: "flex", gap: "1rem" }}>
            <Typography>{item.title}</Typography>
            <img src={item.image} className={classes.productImage}></img>
            <Typography>${(item.quantity * item.price).toFixed(2)}</Typography>

            <ButtonGroup size="small">
              <Button
                type="button"
                onClick={
                  item.quantity > 1 ? () => decreaseQuantity(index) : null
                }
              >
                -
              </Button>
              <Button>{item.quantity}</Button>
              <Button type="button" onClick={() => increaseQuantity(index)}>
                +
              </Button>
            </ButtonGroup>

            <Button onClick={() => removeItem(index)}>Remove</Button>
          </Grid>
          <Grid item xs={1} />
        </Grid>

Upvotes: 7

Related Questions