How to make React + MUI component mobile responsive?

I have a React component created using Material-UI (MUI) that I’m trying to make mobile responsive. Currently, it looks like this:

Now, it looks like this

But I want it to look like this

It should look like this

Here’s the relevant code for the component:

import React from 'react';
import {
  Box, Typography, Paper, Rating, Avatar,
} from '@mui/material';


type CarInfoProps = {
  title: string;
  imageUrl: string;
  rating: number;
  comments: string[];
};

const CarInfo: React.FC<CarInfoProps> = ({
  title, imageUrl, rating, comments,
}) => {
  return (
    <Box
      display="flex"
      flexDirection="column"
      alignItems="center"
      justifyContent="center"
      height="100vh"
    >
      <Paper elevation={3}
        style={{
          padding: '16px', display: 'flex', flexDirection: 'column', alignItems: 'center', height: '980px', width: '955px',
        }}>
        <Typography variant="h5" gutterBottom style={{ textAlign: 'center' }}>
          {title}
        </Typography>
        <Avatar alt={title} src={imageUrl} style={{ marginTop: '16px' }} />
        <Box style={{ marginTop: '16px' }}>
          <Typography variant="body1">Car Info:</Typography>
          {/* Add additional car information here */}
        </Box>
        <Box style={{ marginTop: '16px' }}>
          <Typography variant="body1">Rating:</Typography>
          <Rating value={rating} readOnly />
        </Box>
        <Box style={{ marginTop: '16px' }}>
        </Box>
      </Paper>
    </Box>
  );
};

export default CarInfo;

I’ve tried a lot of different things, but I’m facing challenges achieving the desired mobile responsiveness. Can someone provide guidance on how to structure the styles or any MUI-specific considerations to achieve the desired mobile layout?

I asked the same question yesterday, but I don’t find solution and it is very urgent task!

I really hope that you will help me!

Dynamic Workspace Details Display in Next.js13: Passing Props from Navbar to HomePage

I have a nextjs13 application in which I have mapped over a list of workspaces in Navbar.jsx file.What my main objective is to display the particular workspaces details on the HomePage.jsx which will be distinguished by the workspace_id received in a json object.

When clicked on a particular mapped workspace, HomePage.jsx should be dynamically change accordingly

The relevant info should be passed from the Navbar.jsx to HomePage.jsx as props

I have tried passing the props but it doesn’t work for me

Below are the Navbar.jsx, HomePage.jsx, layout.jsx (navbar component called here for the whole app) page.js (Homepage component called here), Json object example

Navbar.jsx->

import {
  Box,
  Drawer,
  Typography,
  Button,
  Avatar,
  MenuItem,
  Menu,
  IconButton,
} from "@mui/material";
import React, { useEffect, useState, useContext } from "react";
import AccountCircleIcon from "@mui/icons-material/AccountCircle";
import PersonAddIcon from "@mui/icons-material/PersonAdd";
import HomeIcon from "@mui/icons-material/Home";
import ReplayIcon from "@mui/icons-material/Replay";
import IosShareIcon from "@mui/icons-material/IosShare";
import UploadIcon from "@mui/icons-material/Upload";
import { useRouter } from "next/navigation";
import { Lock } from "@mui/icons-material";
import services from "../utils/services";
import ArrowDropDownIcon from "@mui/icons-material/ArrowDropDown";
import ArrowDropUpIcon from "@mui/icons-material/ArrowDropUp";

import get_workspaces_and_roles from "../apis/get_workspaces_and_roles";
import { Workspaces, Workspace } from "../types/workspace_types";
import AddWorkspacePopup from "./AddWorkspacePopup";

const NavBar = ({ onSelectWorkspace }) => {
  const [workspaces, setWorkspace] = useState(null);
  const [isOpen, setIsOpen] = useState(false);
  const [selectedWorkspaceId, setSelectedWorkspaceId] = useState(null);
  const [selectedWorkspaceName, setSelectedWorkspaceName] = useState(null);
  const get_workspaces_hook = () => {
    const user = services.get_user();
    var email = user?.email ?? "";
    const payload = {
      email: "[email protected]",
    };
    if (payload.email === "") {
      alert("Please select an email");
    } else {
      const workspaces = new Workspaces();
      get_workspaces_and_roles(payload)
        .then((response) => {
          console.log(response.data);
          const available_space = response.data.available_space ?? 0.0;
          const available_workspace = response.data.available_workspace ?? 0; //  your workspaces
          const total_workspaces = response?.data?.data ?? []; // your workspaces
          total_workspaces.forEach((element) => {
            const workspace = new Workspace(
              element?.workspace_name ?? "",
              element?.created_at ?? 0,
              element?.workspace_id ?? "",
              element?.role_id ?? "",
              element?.role ?? "",
              element?.owner ?? ""
            );
            workspaces.add_workspace(workspace);
          });
          workspaces.add_meta(available_space, available_workspace);
          setWorkspace(workspaces);
        })
        .catch((error) => {
          console.log(error);
          // alert(error.response.data.message);
        });
    }
  };

  if (!workspaces) get_workspaces_hook();

  const router = useRouter();
  return (
    <>
      <Box
        display="flex"
        flexDirection="column"
        overflow="auto"
        sx={{ backgroundColor: "#15141D" }}
      >
        <Typography
          sx={{
            fontSize: "25px",
            fontWeight: "bold",
            width: "32vh",
            m: "10px",
            cursor: "pointer",
          }}
          onClick={() => router.push("/")}
        >
          PrevRun
        </Typography>
        <Box
          sx={{
            height: "92vh",
            width: "40vh",
            display: "flex",
            flexDirection: "column",
            alignItems: "flex-start",
            justifyContent: "space-between",
            p: "10px",
            overflow: "auto",
            borderRight: ".5px solid black",
          }}
        >
          <Box>
            <Box
              sx={{ borderBottom: ".5px solid white" }}
              display="flex"
              alignItems="center"
            >
              <IconButton
                size="large"
                aria-label="ac count of current user"
                aria-controls="menu-appbar"
                aria-haspopup="true"
                color="inherit"
              >
                <Avatar
                  sx={{
                    height: "25px",
                    width: "25px",
                  }}
                />
              </IconButton>
              <Typography>Utsav</Typography>
            </Box>

            <Typography sx={{ color: "white", m: "15px" }}>Menu</Typography>
            <Box
              sx={{
                height: "35vh",
                width: "100%",
                overflowY: "auto",
              }}
            >
              {workspaces?.get_workspaces().workspaces.map((workspace) => (
                <Button
                  key={workspace.workspace_id}
                  onClick={() => {
                    setSelectedWorkspaceId(workspace.workspace_id);
                    setSelectedWorkspaceName(workspace.workspace_name);
                    console.log(
                      "Selected Workspace ID:",
                      workspace.workspace_id
                    );
                    console.log(
                      "Selected Workspace name:",
                      workspace.workspace_name
                    );
                    console.log("Workspace Object:", workspace);
                    onSelectWorkspace(workspace.workspace_id);
                    router.push("/");
                  }}
                  sx={{
                    display: "flex",
                    justifyContent: "start",
                    width: "100%",
                    my: "5px",
                    fontSize: ".8rem",
                  }}
                >
                  <AccountCircleIcon sx={{ mr: "8px" }} />
                  {workspace.workspace_name}
                </Button>
              ))}
            </Box>
            <Button
              style={{ textAlign: "left" }}
              sx={{
                display: "flex",
                justifyContent: "start",
                width: "100%",
                textAlign: "left",
                fontSize: ".8rem",
                mt: "30px",
                color: "cyan",
              }}
              onClick={() => setIsOpen(true)}
            >
              <PersonAddIcon sx={{ mr: "8px" }} />
              Add Workspace
            </Button>
          </Box>
          <Box
            display="flex"
            flexDirection="column"
            alignItems="flex-start"
            sx={{ mb: "10px" }}
          >
            <Button
              sx={{
                fontSize: ".8rem",
                width: "100%",
                display: "flex",
                justifyContent: "start",
              }}
              onClick={() => router.push("/")}
            >
              <HomeIcon sx={{ mr: "8px" }} />
              Home
            </Button>
            <Button
              sx={{
                fontSize: ".8rem",
                width: "100%",
                display: "flex",
                justifyContent: "start",
              }}
            >
              <ReplayIcon sx={{ mr: "8px" }} />
              Revision Required
            </Button>
            <Button
              sx={{
                fontSize: ".8rem",
                width: "100%",
                display: "flex",
                justifyContent: "start",
              }}
            >
              <IosShareIcon sx={{ mr: "8px" }} />
              Sent For Approval
            </Button>
            <Button
              sx={{
                fontSize: ".8rem",
                width: "100%",
                display: "flex",
                justifyContent: "start",
              }}
              onClick={() =>
                // view_video("basketball.mp4")
                router.push("/uploadvideo")
              }
            >
              <UploadIcon sx={{ mr: "8px" }} />
              Upload video
            </Button>
            <Button
              sx={{
                fontSize: ".8rem",
                width: "100%",
                display: "flex",
                justifyContent: "start",
              }}
              onClick={() => router.push("/auth")}
            >
              <Lock sx={{ mr: "8px" }} />
              Login
            </Button>
          </Box>
        </Box>
      </Box>
      <AddWorkspacePopup isOpen={isOpen} setIsOpen={setIsOpen} />
    </>
  );
};

export default NavBar;

HomePage.jsx ->

"use client";
import { Box, Drawer, Button, Typography } from "@mui/material";
import React, { useEffect, useState } from "react";
import RevisionRequiredVideos from "./RevisionRequiredVideos";
import Header from "../components/Header";
import SentForApproval from "./SentForApproval";
import ApprovedVideos from "./ApprovedVideos";
import RejectedVideos from "./RejectedVideos";
import FailedVideos from "./FailedVideos";
import UploadedVideos from "./UploadedVideos";
import axios from "axios";
import get_workspace_data from "../apis/get_workspace_data";
import { Upload } from "@mui/icons-material";

const HomePage = () => {
  const [revesionRequiredVideos, setRevesionRequiredVideos] = useState([]);
  const [approvalRequiredVideos, setApprovalRequiredVideos] = useState([]);
  const [approvedVideos, setApprovedVideos] = useState([]);
  const [rejectedVideos, setRejectedVideos] = useState([]);
  const [failedVideos, setFailedVideos] = useState([]);
  const [uploadedVideos, setUploadedVideos] = useState([]);

  const [ownerRoleID, setOwnerRoleID] = useState("");

  useEffect(() => {
    get_workspace_data({ workspace_id: "12121212-e423-r4322-133422r3M" })                 
//dynamic render of workspace_id

      .then((res) => {
        console.log(res?.data);
        setOwnerRoleID(
          res?.data?.members?.filter((member) => {
            if (member?.role === "owner") {
              return member?.role_id;
            }
          })
        );
        setRevesionRequiredVideos(
          res?.data?.videos?.filter((video) => {
            if (video?.status === "revision_required") {
              return video;
            }
          })
        );
        setApprovalRequiredVideos(
          res?.data?.videos?.filter((video) => {
            if (video?.status === "approval_required") {
              return video;
            }
          })
        );
        setApprovedVideos(
          res?.data?.videos?.filter((video) => {
            if (video?.status === "approved") {
              return video;
            }
          })
        );
        setRejectedVideos(
          res?.data?.videos?.filter((video) => {
            if (video?.status === "rejected") {
              return video;
            }
          })
        );
        setFailedVideos(
          res?.data?.videos?.filter((video) => {
            if (video?.status === "failed") {
              return video;
            }
          })
        );
        setUploadedVideos(
          res?.data?.videos?.filter((video) => {
            if (video?.status === "uploaded") {
              return video;
            }
          })
        );
      })
      .catch((e) => console.log(e));
  }, []);
  console.log(revesionRequiredVideos);
  console.log(approvalRequiredVideos);
  const [user, setUser] = useState("");
  const [s3_key, setS3Key] = useState("");

  return (
    <Box>
      <Header title={`${user}'s workspace`} />
      <RevisionRequiredVideos
        revesionRequiredVideos={revesionRequiredVideos}
        s3_key={s3_key}
        ownerRoleID={ownerRoleID}
      />
      <SentForApproval
        approvalRequiredVideos={approvalRequiredVideos}
        s3_key={s3_key}
        ownerRoleID={ownerRoleID}
      />
      <ApprovedVideos
        approvedVideos={approvedVideos}
        s3_key={s3_key}
        ownerRoleID={ownerRoleID}
      />
      <RejectedVideos
        rejectedVideos={rejectedVideos}
        s3_key={s3_key}
        ownerRoleID={ownerRoleID}
      />
      <FailedVideos
        failedVideos={failedVideos}
        s3_key={s3_key}
        ownerRoleID={ownerRoleID}
      />
      <UploadedVideos
        uploadedVideos={uploadedVideos}
        s3_key={s3_key}
        ownerRoleID={ownerRoleID}
      />
    </Box>
  );
};

export default HomePage;

layout.js->

"use client"
import { Poppins } from "next/font/google";
import "./globals.css";
import ThemeRegistry from "../../theme/ThemeRegistry";
import TestingComponent from "./apis/testing_component";
import NavBar from "./components/Navbar";
import { Box } from "@mui/material";
import Auth from "./components/Auth";
import { useState } from "react";

const poppins = Poppins({
  subsets: ["latin"],
  weight: ["400", "500", "600", "700", "800", "900"],
});

export default function RootLayout({ children }) {
  const [isLogedIn, setIsLogedIn] = useState(true);

  const handleSelectWorkspace = (selectedWorkspace) => {
    console.log("Selected Workspace in layout.js:", selectedWorkspace);
  };
  const [selectedWorkspaceId, setSelectedWorkspaceId] = useState(null); 


  return (
    <>
      {!isLogedIn ? (
        <html>
          <head />
          <body>
            <Box>
              <Auth isLogedIn={isLogedIn} setIsLogedIn={setIsLogedIn} />
            </Box>
          </body>
        </html>
      ) : (
        <ThemeRegistry>
          <html>
            <head />
            <body>
              <Box display="flex" sx={{ width: "100%", overflow: "auto" }}>
                <Box sx={{ width: "20%", position: "sticky" }}>
                  <NavBar onSelectWorkspace={handleSelectWorkspace} selectedWorkspaceId={selectedWorkspaceId} />
                </Box>
                <Box sx={{ width: "80%", overflow: "auto" }}>
                  <main className={poppins.className}>{children}</main>
                </Box>
              </Box>
              {/* <ToastContainer/> */}
            </body>
          </html>
        </ThemeRegistry>
      )}
    </>
  );
}

page.js ->

import HomePage from "./components/HomePage";

export default function Home() {
  return <HomePage/>
}

Json object ->

 {
      workspace_name: 'random',
      owner: '[email protected]',
      created_at: '1703438656.809325',
      workspace_id: '7d3b9f4e-95b1-4c67-8a82-ee9bc6ac8fa0',
      role_id: '2f6a8b7d-813c-4a9d-af19-cf67e3d2b5a5',
      role: 'owner',
      oauth_configured_email: ''
    }

Keystone.js isAdmin var mentioned in documentation not working

I’m currently working on a KeystoneJS project and encountering an issue with TypeScript. I’ve defined an access control function, isAdmin, as suggested in the KeystoneJS documentation:

const isAdmin = ({ session }: { session: Session }) => session?.data.isAdmin;

However, when I use this function in the access configuration for list operations (create, delete) in my schema.ts, TypeScript throws the following error:

Type '() => boolean' is not assignable to type 'ListOperationAccessControl<"create" | "delete", TypeInfo<any>>'.
Types of parameters '__0' and 'args' are incompatible.
Type 'BaseAccessArgs<TypeInfo<any>> & { operation: "create"; }' is not assignable to type '{ session: Session; }'.
Property 'session' is optional in type 'BaseAccessArgs<TypeInfo<any>> & { operation: "create"; }' but required in type '{ session: Session; }'.

Here’s a simplified version of my schema.ts:

import { list } from "@keystone-6/core";
import type { Lists } from ".keystone/types";

type Session = {
  data: {
    id: string;
    isAdmin: boolean;
  };
};

const isAdmin = ({ session }: { session: Session }) => session?.data.isAdmin;

export const lists: Lists = {
  User: list({
    access: {
      operation: {
        create: isAdmin,
        delete: isAdmin,
      },
      // ... other access controls
    },
    fields: {
      // ... other fields
    },
  }),

  // ... other lists
};

Additionally, I find it interesting that the built-in allowAll function in node_modules/@keystone-6/core/src/access.ts, which simply returns true, works without any issues.

export function allowAll() {
  return true;
}

But when I tried to the same thing for isAdmin is still does not work.

function isAdmin() {
  return true;
}

I tried to debug by using the valid inbuilt function (allowAll) as local function (isAdmin) with same logic but it still doesn’t work.

When I run npm run dev it still works, but when I run npm run test it wouldn’t.

npm run test is just running jest.

Automatic POST requests validator Express

I’m using express-validator and I’m trying to create a middleware that applies to every post request, finds the right validator for the request and calls the right method for the validation.
The validators are objects, exported from files in the /validators folder, the names of the files are related to the requests so that the validation midlleware can import the right validator from the request’s path (ex: the validator for the post to /auth/checkSignup is the file /validators/auth.js);
each validator has one (or more) validation method called ‘check’ where actionName is a part of the request’s path (in the example above ‘checkSignup’ is the action, so the AuthValidator has the method checkLogin).

ex of thw middleware called in the app.js file:

app.post(
    '*',
    ValidationDispatcher.validationMiddleware
);

the middleware should read the req.path and find the appropriate validator for the route (eg: the pathg is /auth/signup the validator is the one exported by the file auth.js, leaving out the folders), after that it should find the appropriate method (in the example above, the method is checkSignup); every method for the validation is similar to this:

checkSignup() {
        return expressValidator.checkSchema({
            email: {
                ...this.baseEmailSchema,
                custom: {
                    options: (value) => {
                        return UsersController.getByEmail(value).then((res) => {
                            return res != null;
                        });
                    },
                    errorMessage: "user with this email already exists",
                },
            },
            password: this.basePasswordSchema,
            confirmPassword: {
                custom: {
                    options: (value, { req }) => {
                        return value === req.body.password;
                    },
                    errorMessage: "passwords have to match",
                },
            },
        });
    }

but with this approach I’m returning a middleware that will not be executed;
does anyone have any ideas?

{1:’a’}[1] This syntax works in code but not in the browser’s developer tools?

I’ve taken on a new project,and there’s a line of code that looks like this:

typeName() {
      return {
        1: 'leads',
        2: 'cunstomer',
        3: 'business'
      }[this.optionValue]
    },

it works well.
I’ve never seen before.
Then I tried in developer tools,but it don’t work!
Can anyone tell me why?
enter image description here

{1:'a'}[1]

Developer tools will report the error:Uncaught SyntaxError: Unexpected token ‘:’

The key-down event invalid in zoom out when using ARCGIS JavaScript in EPSG:3826

I am a newbie to ARCGIS JAVASCRIPT. And I meet a problem when the tileLayer load in, and the zoom controller I set in the top-right is not work well. The plus button can only be invoked event two or three times, and then not working any more, and the minus button can work well. In another aspect of moues, the mouse-wheel event can zoom out/in in perfect behavior. my version is 4.10, my environment is node.js with express, the code snippet is as following:

const basemap = new Basemap({
    baseLayers: [
        new TileLayer({
            url: "https://arcgis.tpgos.gov.taipei/arcgis/rest/services/ED/GD_Plain_Service/MapServer",
            title: "Basemap",
            crossOrigin: 'anonymous',
            spatialReference: {
                wkid: 102443
            }
        })
    ],
    title: "basemap",
    id: "basemap",
    spatialReference: {
        wkid: 102443
    }
});


// Create a map using the MapImageLayer
var map = new Map({
    basemap: basemap
});


var view = new MapView({
    container: "divmap",
    map: map,
    zoom: 3,
    extent: {
        xmin: 296938.73458000005,
        ymin: 2776832.77203,
        xmax: 301876.2566600001,
        ymax: 2781271.34259,
    },
    crossOrigin: 'anonymous',
    spatialReference: {
        wkid: 102443
    } // Set the spatial reference
   
});
view.ui.move("zoom", "top-right");

is anyone know the exactly reason? and how to fix that, thanks a lot.

When clicking a link, navigate to a specific element in React without scrolling

In my user’s profiles page in React, when clicking on an image, it currently scrolls to that specific image within the entire images page. However, I want it to navigate directly to that image element without scrolling. I want to make this change because it becomes very lag when there are 100 pictures in a user’s profile.

Is there any method in react or nextjs to achieve this?

How do I format a code block in markdown?

I get a response from the server which is in a string format, I want to render it with the proper formatting for that language, and not be a single line code.

the response from the server

let response = “function hero(){ console.log(“Hello, world!”); }” [contains back thick at the beginning and end]

I want it to be rendered with formatting like this:

function hero(){
    console.log("Hello, world!");
}

Any comment or advice is appreciated

React – Filtering Cards based on Selected Value from Autocomplete

I have a React application where I’m using Material-UI’s Autocomplete component to filter a cards based on a selected brand. The cards represent different car models, and I want to filter them when a user selects a brand from the Autocomplete dropdown.

Here’s the appropriate code:

The filter:


import * as React from 'react';
import TextField from '@mui/material/TextField';
import Autocomplete from '@mui/material/Autocomplete';

const top100Cars = [
  { label: 'Toyota' },
  { label: 'Ford' },
  { label: 'Chevrolet' },
  { label: 'Tesla' },
  { label: 'Honda' },
  { label: 'BMW' },
  { label: 'Audi' },
  { label: 'Mercedes-Benz' },
  { label: 'Ferrari' },
  { label: 'Porsche' },
  { label: 'Lamborghini' },
  { label: 'Nissan' },
  { label: 'Volkswagen' },
  { label: 'Mazda' },
  { label: 'DeLorean' },
  { label: 'Dodge' },
];


export default function searchBar() {

  const [selectedBrand, setSelectedBrand] = React.useState(null);

  return (
    <Autocomplete
      disablePortal
      id="combo-box-demo"
      options={top100Cars}
      value={selectedBrand}
      onChange={(event, newValue) => {
        setSelectedBrand(newValue);
      }}
      sx={{
        width: 254, backgroundColor: 'white', borderRadius: 50,
      }}
      renderInput={(params) => (
        <TextField
          {...params}
          label="Марка"
          size='small'
        />
      )}
    />
  );
}

The code of one of the cards:

import * as React from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { styled } from '@mui/material/styles';
import Card from '@mui/material/Card';
import CardHeader from '@mui/material/CardHeader';
import CardMedia from '@mui/material/CardMedia';
import Checkbox from '@mui/material/Checkbox';
import FormControlLabel from '@mui/material/FormControlLabel';
import FormGroup from '@mui/material/FormGroup';
import IconButton, { IconButtonProps } from '@mui/material/IconButton';
import Typography from '@mui/material/Typography';
import Rating from '@mui/material/Rating';
import Grid from '@mui/material/Grid';
import Button from '@mui/material/Button';
import LocationOnIcon from './SVGiCON';

type ExpandMoreProps = IconButtonProps & {
  expand: boolean;
};

const ExpandMore = styled((props: ExpandMoreProps) => {
  const { expand, ...other } = props;

  const label = { inputProps: { 'aria-label': 'Checkbox demo' } };

  return <IconButton {...other} />;
})(({ theme, expand }) => ({
  transform: !expand ? 'rotate(0deg)' : 'rotate(180deg)',
  marginLeft: 'auto',
  transition: theme.transitions.create('transform', {
    duration: theme.transitions.duration.shortest,
  }),
}));

type RecipeReviewCardProps = {
  to: string; // Specify the destination when the button is clicked
  // Add any additional props you may need
};

export const RecipeReviewCard: React.FC<RecipeReviewCardProps> = ({ to }) => {
  const [expanded, setExpanded] = React.useState(false);
  const navigate = useNavigate();

  const handleExpandClick = () => {
    setExpanded(!expanded);
  };
  const [state, setState] = React.useState({
    gilad: false,
    jason: false,
    antoine: false,
  });

  const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setState({
      ...state,
      [event.target.name]: event.target.checked,
    });
  };

  const { gilad, jason, antoine } = state;

  const [value, setValue] = React.useState<number | null>(2);

  const handleButtonClick = () => {
    navigate(to);
  };

  return (
    <Card style={{
      width: '312px', height: '285px', backgroundColor: "gray",
    }}>
      <CardHeader
        title="Ауди, А4"
        subheader="София, София-град"
        // titleTypographyProps={{
        //   fontSize: 22,
        // }}
        subheaderTypographyProps={{
          color: "white",
        }}
        style={{
          textAlign: 'center', fontSize: '1px', marginBottom: '-10px', marginTop: '-9px', color: "white",
        }}
      />
      <Grid container>
        <Grid item xs={6}>
          {/* Adjust the width and height of the image as needed */}
          <CardMedia
            component="img"
            height="84.28px"
            image="https://images.pexels.com/photos/244212/pexels-photo-244212.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1"
            style={{ marginLeft: '10px' }}
          />
        </Grid>
        <Grid item
          xs={6}
          sx={{
            width: '43px', top: '6px', left: '245px', height: '17px', // Set the width to 100% or adjust as needed
          }}>
          <Typography style={{
            display: 'flex', alignItems: 'center', marginLeft: '20px', fontSize: '14px', color: "white",
          }}>
            <LocationOnIcon style={{ marginRight: '10px', width: '15px', height: '15px' }} />
            Дизел
          </Typography>
          <Typography style={{
            display: 'flex', alignItems: 'center', marginLeft: '20px', fontSize: '14px', color: "white",
          }}>
            <LocationOnIcon style={{ marginRight: '10px', width: '15px', height: '15px' }} />
            Бял
          </Typography>
          <Typography style={{
            display: 'flex', alignItems: 'center', marginLeft: '20px', fontSize: '14px', color: "white",
          }}>
            <LocationOnIcon style={{ marginRight: '10px', width: '15px', height: '15px' }} />
            2013 г.
          </Typography>
          <Typography style={{
            display: 'flex', alignItems: 'center', marginLeft: '20px', fontSize: '14px', color: "white",
          }}>
            <LocationOnIcon style={{
              marginRight: '10px', width: '15px', height: '15px', color: "white",
            }} />
            290 000 км
          </Typography>
        </Grid>
      </Grid>

      <FormGroup style={{ marginLeft: '10px', marginTop: '11px' }}>
        <FormControlLabel
          style={{ marginBottom: '-10px', color: "white" }}
          control={
            <Checkbox
              checked={gilad}
              onChange={handleChange}
              name="gilad"
              size='small'
              style={{ color: 'white' }} />
          }
          label="Реален пробег"
        />
        <FormControlLabel
          style={{ color: "white" }}
          control={
            <Checkbox checked={jason}
              onChange={handleChange}
              name="jason"
              size='small'
              style={{ color: 'white' }} />
          }
          label="Първи собственик"
        />
      </FormGroup>
      <Typography
        component="legend"
        style={{ marginLeft: "8px", fontSize: '13px', color: "white" }}
      >Рейтинг
      </Typography>

      <Grid container>
        <Grid item xs={12} style={{ marginLeft: '8px', display: 'flex', alignItems: 'center' }}>
          <Rating name="read-only" value={value} readOnly size="small" />
          <Link to={to}>
            <Button
              variant="contained"
              color="success"
              style={{
                marginLeft: '88px',
                width: '103px',
                height: '24px',
                fontSize: '10px',
                borderRadius: '50px',
              }}
              onClick={handleButtonClick}
            >
              Виж повече
            </Button>
          </Link>
        </Grid>
      </Grid>
    </Card>
  );
};

This below is the container component that contains all of the cards

import * as React from 'react';
import Grid from '@mui/material/Grid';
import { RecipeReviewCard } from './CardTemplate';


export default function ResponsiveCardContainer() {
  return (
    <Grid container justifyContent="center" spacing={5} marginTop={10} paddingBottom={5}>
      <Grid item>
        <RecipeReviewCard to="/more-info/:id" />
      </Grid>
      <Grid item>
        <RecipeReviewCard to="/more-info/:id" />
      </Grid>
      <Grid item>
        <RecipeReviewCard to="/more-info/:id" />
      </Grid>
      <Grid item>
        <RecipeReviewCard to="/more-info/:id" />
      </Grid>
    </Grid>
  );
}

And this below is the code in the main.tsx

const DefaultComponent: React.FC = () => {
  return (
    <>
      {sections.map(({ component, sectionId }) => (
        <SectionContainer key={sectionId} sectionId={sectionId}>
          {component}
        </SectionContainer>
      ))}
      <MultiSearchBar />
      <ResponsiveCardContainer />
    </>
  );
};

It looks like this right now:

[![Here is how it looks right now][1]][1]

However, the filtering is not working as expected. When I select a brand, the cards are not updating accordingly. This because I don’t know how to implement the logic for this.

I know that maybe my existing implementation is not perfect, will appreciate any suggestions.

It is urgent task and I will be more than happy if someone help me!

Can someone help me?

Fail to use v-bind on img src in vue3

Now I’m building a vue3 project in vite. But I found a weird error.

The following code work perfectly:

<template>
  <img src="@/assets/images/pics/cover_info.jpeg">
</template>
<script>
export default {
  name: 'Image',
  data() {
  return {
    
  };
}
};
</script>

While I change to v-bind, the server failed to load the img

<template>
  <img :src="ImgUrl">
</template>
<script>
export default {
  name: 'Image',
  data() {
  return {
    ImgUrl: '@/assets/images/pics/cover_info.jpeg',
  };
}
};
</script>

the console show following info:
GET http://localhost:5173/assets/images/pics/cover_info.jpeg 404 (Not Found)

Thank you for your patient and hope for your reply.

How to wrap an input file in a form using javascript?

I have a function:-

function resetInputFile(elem) {
    elem.wrap('<form>').closest('form').get(0).reset();
    elem.unwrap();
}

I call the function like this:-

resetInputFile(document.queryElement('#image'));

How can I convert the LOCs

elem.wrap('<form>').closest('form').get(0).reset();
elem.unwrap();

into pure javascript?

I want to implement the logic in ReactJS, but I don’t want to use jquery with ReactJS. So I need to do it with pure javascript.

how to properly replace hyphen with div elements in javascript

I have the following text stackoverflow-is-the-best-site-in-the-world by hyphen. I need to replace those hyphen and surround each text within div tags as per result sample below

<div class='cssx'>stackoverflow</div>
<div class='cssx'>is</div>
<div class='cssx'>the</div>
<div class='cssx'>best</div>
<div class='cssx'>in</div>
<div class='cssx'>the</div>
<div class='cssx'>world</div>

In PHP I can get it working as follow.

<?php
$str ="stackoverflow-is-the-best-site-in-the-world";
echo $output = str_replace('-', "<div class='cssx'></div>", $str);

?>

Here is my issue. I need to get it working with javascript. To this effect, I have leveraged solution here
source

but cannot get it to work.

here is the code so far.

const str ="stackoverflow-is-the-best-site-in-the-world";

var output = "<div class='cssx'>" + 
"text.replace(/-/g, "</div><div class='cssx'>", str)" +
 "</div>";

alert(output);

I am getting an error in dispatch sign up using CreateAsyncThunk, I could not dispatch it

enter image description here

I am working on integrating Redux into my project, specifically focusing on user authentication. Below is the code snippet for my authUserSlice. I am encountering an issue when trying to dispatch the signup action in a NextJS Component. Despite handling the promise with a try-catch block, I am facing difficulties.

import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import authService from './authService';

interface Form {
  fullname: string;
  username: string;
  password: string;
  dateofbirth: string;
  status: string;
}

interface AuthState {
  user: Form | null;
  isError: boolean;
  isSuccess: boolean;
  isLoading: boolean;
  message: string;
}

const initialState: AuthState = {
  user: null,
  isError: false,
  isSuccess: false,
  isLoading: false,
  message: '',
};

// Register user
export const signup = createAsyncThunk(
  'user/register',
  async (user: Form, thunkAPI) => {
    try {
      const response = await authService.signup(user);
      return response.data; 
    } catch (error) {
      return thunkAPI.rejectWithValue(error);
    }
  }
);

export const authSlice = createSlice({
  name: 'user',
  initialState,
  reducers: {
    resetAuthUser: (state) => {
      state.isLoading = false;
      state.isSuccess = false;
      state.isError = false;
      state.message = '';
      state.user = null;
    },
  },
  extraReducers: (builder) => {
    builder
      .addCase(signup.pending, (state) => {
        state.isLoading = true;
      })
      .addCase(signup.fulfilled, (state, action) => {
        state.isLoading = false;
        state.isSuccess = true;
        state.user = action.payload;
      })
      .addCase(signup.rejected, (state, action) => {
        state.isLoading = false;
        state.isError = true;
        state.message = action.payload as string;
        state.user = null;
      });
  },
});

export const { resetAuthUser } = authSlice.actions;
export default authSlice.reducer;

//This is my sample sign up form, i filled out the formData with sample data.

import React, { useState } from 'react';
import type { RootState } from '@/lib/store';
import { unwrapResult } from '@reduxjs/toolkit';
import { useSelector, useDispatch } from 'react-redux';
import { signup, resetAuthUser } from '@/lib/features/authUserSlice'; // Import reset action

interface Form {
  fullname: string,
  username: string;
  password: string;
  dateofbirth: string;
  status: string;
}

const SignUp = () => {
  const [formData, setFormData] = useState<Form>({
    fullname: 'Dummy Name',
    username: 'Dummy122',
    password: 'Dummy1234',
    dateofbirth: '',
    status: ''
  });

  const { username, password } = formData;
  const count = useSelector((state: RootState) => state.counter.value);
  const dispatch = useDispatch();

  const onSubmit = async () => {
  

    dispatch(signup(formData))

  };

I tried changing the type, i thought it would resolve the problem and still getting the same error.

Stored Procedure [closed]

Can you please help me to identify the back up tables,views in the database and write a procedure to keep latest 3 backup tables in the database and rest of the backup should be drop/delete.

Thanks & Regards,
Uday

I need to solution for this