How to add search functionality to the SearchAppBar in Material UI? - javascript

So I have a basic react app that allows the user to search for and display movies from the Movie Database API.
Heres the problem: I want to link my custom React Function SearchMovies() to a material ui component, specifically the Material Ui SearchAppBar. However, I am having trouble adding this function to the Material Ui SearchAppBar.
First, my custom code that features the SearchMovies() function. The code is below:
import React, { useState } from "react";
import MovieCard from "./movieCard";
export default function SearchMovies() {
//states = input query, movies
const [query, setQuery] = useState("");
const [movies, setMovies] = useState([]);
const searchMovies = async (e) => {
e.preventDefault();
const url = `https://api.themoviedb.org/3/search/movie?api_key=a2657ca16cc801deb9a65e9f7f9e3d4f&language=en-US&query=${query}&page=1&include_adult=false`;
try {
const res = await fetch(url);
const data = await res.json();
//console.log(data.results);
setMovies(data.results);
} catch (err) {
console.error(err);
}
};
return (
<>
<form className="form" onSubmit={searchMovies}>
<label className="label" htmlFor="query">
Movie Name
</label>
<input
type="text"
className="input"
name="query"
placeholder="i.e. Star Wars"
value={query}
onChange={(e) => setQuery(e.target.value)}
/>
<button className="button" type="Submit">
Search
</button>
</form>
<div className="card-list">
{movies
.filter((movie) => movie.poster_path)
.map((movie) => (
<MovieCard movie={movie} key={movie.id} />
))}
</div>
</>
);
}
Second, here is the code for the Material UI SearchAppBar:
import React from "react";
import AppBar from "#material-ui/core/AppBar";
import Toolbar from "#material-ui/core/Toolbar";
import IconButton from "#material-ui/core/IconButton";
import Typography from "#material-ui/core/Typography";
import InputBase from "#material-ui/core/InputBase";
import { fade, makeStyles } from "#material-ui/core/styles";
import MenuIcon from "#material-ui/icons/Menu";
import SearchIcon from "#material-ui/icons/Search";
import searchMovies from "./searchMovies";
const useStyles = makeStyles((theme) => ({
root: {
flexGrow: 1,
},
menuButton: {
marginRight: theme.spacing(2),
},
title: {
flexGrow: 1,
display: "none",
[theme.breakpoints.up("sm")]: {
display: "block",
},
},
search: {
position: "relative",
borderRadius: theme.shape.borderRadius,
backgroundColor: fade(theme.palette.common.white, 0.15),
"&:hover": {
backgroundColor: fade(theme.palette.common.white, 0.25),
},
marginLeft: 0,
width: "100%",
[theme.breakpoints.up("sm")]: {
marginLeft: theme.spacing(1),
width: "auto",
},
},
searchIcon: {
padding: theme.spacing(0, 2),
height: "100%",
position: "absolute",
pointerEvents: "none",
display: "flex",
alignItems: "center",
justifyContent: "center",
},
inputRoot: {
color: "inherit",
},
inputInput: {
padding: theme.spacing(1, 1, 1, 0),
// vertical padding + font size from searchIcon
paddingLeft: `calc(1em + ${theme.spacing(4)}px)`,
transition: theme.transitions.create("width"),
width: "100%",
[theme.breakpoints.up("sm")]: {
width: "12ch",
"&:focus": {
width: "20ch",
},
},
},
}));
export default function SearchAppBar() {
const classes = useStyles();
return (
<div className={classes.root}>
<AppBar position="static">
<Toolbar>
<IconButton
edge="start"
className={classes.menuButton}
color="inherit"
aria-label="open drawer"
>
<MenuIcon />
</IconButton>
<Typography className={classes.title} variant="h5" noWrap>
MovieZone
</Typography>
<div className={classes.search}>
<div className={classes.searchIcon}>
<SearchIcon />
</div>
<InputBase
//value={query}
//onChange={(e) => setQuery(e.target.value)}
onSubmit={searchMovies}
placeholder="Search…"
classes={{
root: classes.inputRoot,
input: classes.inputInput,
}}
inputProps={{ "aria-label": "search" }}
/>
</div>
</Toolbar>
</AppBar>
</div>
);
}
So how can I inject the SearchMovies() function into the Material UI SearchAppBar, so that the user can use the Material UI component to call the SearchMovies() function and display the movie results?

You can take the reference from an angular material table example but you have mat cards its just the matter of filtering the dataSource what you give and recall that method or just change the arrayList by constructing filter arraylist or something which you provide again to the UI component
Here is the link
https://stackblitz.com/angular/kgboooaejyn?embed=1&file=src/app/table-filtering-example.ts
you need to focus on this function
applyFilter(event: Event) {
const filterValue = (event.target as HTMLInputElement).value;
this.dataSource.filter = filterValue.trim().toLowerCase();
}
You won't have a Datasource here but you can filter contents from ArrayList
Hope this idea works...!!

Related

How to implement delete function of a row in MUI DataGrid (js)

I have delete icon button in my grid, in each row. It doesn't delete a row however. Could anyone help, please?
I am creating a todo app, and each row got to have its own delete button. For some reason, I can't connect deleteTodo component to that button.
import React, { useState } from 'react';
import './App.css';
import Button from '#mui/material/Button';
import TextField from '#mui/material/TextField';
import AppBar from '#mui/material/AppBar';
import Toolbar from '#mui/material/Toolbar';
import Typography from '#mui/material/Typography';
import IconButton from '#mui/material/IconButton';
import DeleteIcon from '#mui/icons-material/Delete';
import Tooltip from '#mui/material/Tooltip';
import SaveIcon from '#mui/icons-material/Save';
import { DataGrid } from '#mui/x-data-grid';
export default function App() {
const [todo, setTodo] = useState({description: '', date: ''});
const [todos, setTodos] = useState([]);
const inputChanged = (event) => {
setTodo({...todo, [event.target.name]: event.target.value});
}
const addTodo = () => {
const newTodo = {...todo, id: new Date().toString()}
setTodos([...todos, newTodo]);
setTodo({description: '', date: ''});
}
const deleteTodo = (row) => {
setTodos(todos.filter((todo, index) => index !== row));
}
const columns = [
{field: 'description', headerName: 'Description', width: 200},
{field: 'date', headerName: 'Date', width: 200},
{
field: " ",
headerName: " ",
width: 200,
sortable: false,
renderCell: ({index}) => {
return (
<IconButton
size='small'
color='error'
onClick={() => deleteTodo(index)}>
<Tooltip title="Delete todo">
<DeleteIcon />
</Tooltip>
</IconButton>
)
}
}
]
return (
<div className="App">
<AppBar position="static">
<Toolbar>
<Typography variant="h6">
Todolist
</Typography>
</Toolbar>
</AppBar>
<TextField
style={{marginRight: 10}}
variant="standard"
label="Description"
name="description"
value={todo.description}
onChange={inputChanged}
/>
<TextField
variant="standard"
style={{marginRight: 10}}
label="Date"
name="date"
value={todo.date}
onChange={inputChanged}
/>
<Button
style= {{margin: 10}}
startIcon={<SaveIcon />}
color="primary"
variant="outlined"
onClick={addTodo}>
Add
</Button>
<div style={{ height: 300, width: '40%', margin: 'auto' }}>
<DataGrid
rows={todos}
columns={columns}
getRowId={row => row.id}
/>
</div>
</div>
);
}
I tried to use different (line 40) render cell parameters, but it doesn't work.
import React, { useState } from 'react';
import './App.css';
import Button from '#mui/material/Button';
import TextField from '#mui/material/TextField';
import AppBar from '#mui/material/AppBar';
import Toolbar from '#mui/material/Toolbar';
import Typography from '#mui/material/Typography';
import IconButton from '#mui/material/IconButton';
import DeleteIcon from '#mui/icons-material/Delete';
import Tooltip from '#mui/material/Tooltip';
import SaveIcon from '#mui/icons-material/Save';
import { DataGrid, GridColDef } from '#mui/x-data-grid';
export default function App() {
const [todo, setTodo] = useState({description: '', date: ''});
const [todos, setTodos] = useState([]);
const inputChanged = (event) => {
setTodo({...todo, [event.target.name]: event.target.value});
}
const addTodo = () => {
const newTodo = {...todo, id: new Date().toString()}
setTodos([...todos, newTodo]);
setTodo({description: '', date: ''});
}
const deleteTodo = (row) => {
setTodos(todos.filter((todo, index) => index !== row.tabIndex));
}
const columns = [
{field: 'description', headerName: 'Description', width: 200},
{field: 'date', headerName: 'Date', width: 200},
{
field: " ",
headerName: " ",
width: 200,
sortable: false,
align: "center",
renderCell: (params) => {
console.log(params)
return (
<IconButton
size='small'
color='error'
onClick={() => deleteTodo(params)}>
<Tooltip title="Delete todo">
<DeleteIcon />
</Tooltip>
</IconButton>
)
}
}
]
return (
<div className="App">
<AppBar position="static">
<Toolbar>
<Typography variant="h6">
Todolist
</Typography>
</Toolbar>
</AppBar>
<TextField
style={{marginRight: 10}}
variant="standard"
label="Description"
name="description"
value={todo.description}
onChange={inputChanged}
/>
<TextField
variant="standard"
style={{marginRight: 10}}
label="Date"
name="date"
value={todo.date}
onChange={inputChanged}
/>
<Button
style= {{margin: 10}}
startIcon={<SaveIcon />}
color="primary"
variant="outlined"
onClick={addTodo}>
Add
</Button>
<div style={{ height: 300, width: '40%', margin: 'auto' }}>
<DataGrid
rows={todos}
columns={columns}
getRowId={row => row.id}
/>
</div>
</div>
);
}

Passing Data From One Component to Another React

Hey guys and gals i am trying to pass data from a text field in one component to another component. But the component that calls the text field is called in my Home.tsx file while i need the data from my Search.tsx file ( which also has where the text field is created ) to be sent to my searchResults.tsx file. Hope that makes sense
Here is my Home.tsx
import { ChakraProvider, Flex, Heading, IconButton, Input, Spacer, useColorMode, useDisclosure, VStack } from "#chakra-ui/react";
import Search from "../components/Search";
const Home = () => {
return(
<div>
<Flex>
<Search></Search>
</Flex>
</div>
)
}
export default Home
Here is my Search.tsx
import { TextField, IconButton} from "#material-ui/core"
import {Router, SearchOutlined } from '#material-ui/icons';
import { makeStyles } from "#material-ui/core/styles";
import "../App.css";
import { useState } from "react";
import { ChakraProvider,Box, color, position } from "#chakra-ui/react";
import { ReactComponent as Logo } from '../images/logo.svg';
const useStyles = makeStyles({
input: {
color: "blue"
}
})
const Search = () => {
const [searchTerm, setSearchTerm] = useState("");
const [displaySearchTerm, setDisplaySearchTerm] = useState("");
const useStyles = makeStyles((theme) => ({
input: {
color: "#fcba03",
},
}));
const classes = useStyles();
return(
<div>
<div className='searchCont' style={{alignItems: "center", justifyContent: 'center'}} >
<Logo style={{ height: 150, width: 300, position: "absolute", verticalAlign: "middle", marginTop: 200, left: '40%', backgroundColor: '#1a202c', borderRadius: 10 }} />
<TextField
inputProps={{color: classes.input}}
style={{width: 600, display: "flex", position: "absolute", verticalAlign: "middle", backgroundColor: "white", borderRadius: 5, alignItems: "center", justifyContent: 'center', marginTop: 400, marginBottom: 50, left: '32%', marginRight: 200}}
margin="normal"
className="textField"
fullWidth
id="standard-bare"
variant="outlined"
label="Search for Domains..."
onChange={(e) => setSearchTerm(e.target.value)}
InputProps={{
endAdornment: (
<IconButton onClick={() =>{searchTerm}}>
<SearchOutlined />
</IconButton>
),
}}
/>
</div>
</div>
)
}
export default Search
Here is my searchResults.tsx
import { Flex } from "#chakra-ui/react";
import React from "react";
import {searchTerm} from "../components/Search";
const SearchResults = () => {
return(
<div>
<Flex>
<Search data={searchTerm} /> //error here
</Flex>
</div>
)
}
export default SearchResults;
use Redux as your state management system for this, this will help you read and write states across application without worrying.
You can also try react Context if its a one off issue and you dont wana invest into the redux system and its boiler plate code, but if you face this issue more frequently as your project grows complex use redux.

How can I insert a basic Search bar in Material UI Data Grid?

For example: refer this sample data grid.
Want to add a basic search bar like:here
How can I add in Data Grid MUI.
Please guide.
Just create a search bar using a label and text input. Aftermath you can update your grid according to the string in your search box by the search filtered data.
In datagrid there is prop components and Toolbar in that prop to pass whatever component you want.
components={{ Toolbar: QuickSearchToolbar }}
and pass props from
componentsProps={{
toolbar: {
value: searchText,
onChange: (event: React.ChangeEvent<HTMLInputElement>) => handleSearch
},
}}
This is a good example to check out:
import * as React from 'react';
import IconButton from '#mui/material/IconButton';
import TextField from '#mui/material/TextField';
import {
DataGrid,
GridToolbarDensitySelector,
GridToolbarFilterButton,
} from '#mui/x-data-grid';
import { useDemoData } from '#mui/x-data-grid-generator';
import ClearIcon from '#mui/icons-material/Clear';
import SearchIcon from '#mui/icons-material/Search';
import { createTheme } from '#mui/material/styles';
import { createStyles, makeStyles } from '#mui/styles';
function escapeRegExp(value: string): string {
return value.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
}
const defaultTheme = createTheme();
const useStyles = makeStyles(
(theme) =>
createStyles({
root: {
padding: theme.spacing(0.5, 0.5, 0),
justifyContent: 'space-between',
display: 'flex',
alignItems: 'flex-start',
flexWrap: 'wrap',
},
textField: {
[theme.breakpoints.down('xs')]: {
width: '100%',
},
margin: theme.spacing(1, 0.5, 1.5),
'& .MuiSvgIcon-root': {
marginRight: theme.spacing(0.5),
},
'& .MuiInput-underline:before': {
borderBottom: `1px solid ${theme.palette.divider}`,
},
},
}),
{ defaultTheme },
);
interface QuickSearchToolbarProps {
clearSearch: () => void;
onChange: () => void;
value: string;
}
function QuickSearchToolbar(props: QuickSearchToolbarProps) {
const classes = useStyles();
return (
<div className={classes.root}>
<div>
<GridToolbarFilterButton />
<GridToolbarDensitySelector />
</div>
<TextField
variant="standard"
value={props.value}
onChange={props.onChange}
placeholder="Search…"
className={classes.textField}
InputProps={{
startAdornment: <SearchIcon fontSize="small" />,
endAdornment: (
<IconButton
title="Clear"
aria-label="Clear"
size="small"
style={{ visibility: props.value ? 'visible' : 'hidden' }}
onClick={props.clearSearch}
>
<ClearIcon fontSize="small" />
</IconButton>
),
}}
/>
</div>
);
}
export default function QuickFilteringGrid() {
const { data } = useDemoData({
dataSet: 'Commodity',
rowLength: 100,
maxColumns: 6,
});
const [searchText, setSearchText] = React.useState('');
const [rows, setRows] = React.useState<any[]>(data.rows);
const requestSearch = (searchValue: string) => {
setSearchText(searchValue);
const searchRegex = new RegExp(escapeRegExp(searchValue), 'i');
const filteredRows = data.rows.filter((row: any) => {
return Object.keys(row).some((field: any) => {
return searchRegex.test(row[field].toString());
});
});
setRows(filteredRows);
};
React.useEffect(() => {
setRows(data.rows);
}, [data.rows]);
return (
<div style={{ height: 400, width: '100%' }}>
<DataGrid
components={{ Toolbar: QuickSearchToolbar }}
rows={rows}
columns={data.columns}
componentsProps={{
toolbar: {
value: searchText,
onChange: (event: React.ChangeEvent<HTMLInputElement>) =>
requestSearch(event.target.value),
clearSearch: () => requestSearch(''),
},
}}
/>
</div>
);
}

How to use MUI v5+ with class-based react components?

We are trying to update our web application from material ui (v4) to mui (v5)
Using the available examples, we have managed for function based components, but it does not seem to work for class based components, and there is very little examples around on class based components and MUI.
Out pattern looks something like the below currently, but none of the styles are applied to the MUI components. The same pattern seems to work on a POC project with functional components.
The container file Login.js
import {connect} from 'react-redux'
import Layout from '../pages/login.js';
import { call } from '../reducers/helloWorld'
import { logIn, logOut } from "../reducers/userManagement"
const mapStateToProps = state => ({
user: state.userManagement.user,
requestState: state.helloWorld.requestState,
})
const mapDispatchToProps = dispatch => ({
helloWorld: () => dispatch(call()),
logIn: (user2) => dispatch(logIn(user2)),
logOut: () => dispatch(logOut()),
})
export default connect(mapStateToProps, mapDispatchToProps)(Layout)
the page file login.js
import React from "react";
import { Typography, Button, FormControlLabel, Checkbox, TextField, Grid, Paper} from '#mui/material';
import { styled } from '#mui/material/styles';
import theme from '../theme';
import classes from '../styles/login';
import logo from '../img/Ergopak-logo.png';
import { Navigate } from 'react-router-dom';
// SXprops
class Login extends React.Component {
state = {
email: "",
password: "",
showPassword: false,
navigateTo: ""
}
componentDidMount(){
const {logOut} = this.props
logOut()
}
goToHome(){
}
handleSubmit(e){
const {logIn} = this.props
console.log("handleSubmit pressed!!")
logIn({name: "Pieka"})
this.setState({navigateTo: <Navigate to="/home"/>})
}
setEmail(){
console.log("handleEmail pressed")
}
setPassword(){
console.log("setPassword pressed")
}
render(){
const {user, requestState} = this.props
const {email, password, showPassword, navigateTo} = this.state
console.log("requestState", requestState)
console.log("user", user)
console.log("that thing is, ", classes(theme).welcome)
return(
<div style={{backgroundColor: "green", height: "100%", position: "fixed", width: "100%"}}>
<Grid container direction = "column" alignItems="stretch" justifyContent="flex-start" style={{backgroundColor: "grey", height: "100%", display: "flex"}} >
{navigateTo}
<Grid item sx = {classes(theme).welcomeDiv}>
<div sx = {classes(theme).welcome} >Welcome To SightPlan </div>
</Grid>
<Grid item >
<img style={{maxHeight: "2em"}} src={logo} alt="logo" />
</Grid>
<Grid item sx = {classes(theme).centerDivs}>
<Typography>Please log in with your email address and password</Typography>
<TextField
sx={{
width: 400
}}
type="email"
value={email}
placeholder="Email"
onChange={(e) => this.setState({email: e.target.value})}
/>
<Grid container direction = "column" alignItems = "center">
<TextField
sx = {classes(theme).loginFields}
type= {showPassword ? "string" : "password"}
variant="standard"
value={password}
placeholder="Password"
onChange={(e) => this.setState({password: e.target.value})}
/>
<FormControlLabel
control={<Checkbox size="small" name="showClosed" />}
checked={showPassword}
label={<span style={{ fontSize: '0.8em' }}> Show password </span>}
onChange={e => this.setState({showPassword: !showPassword})}
style={{margin: "auto"}}
/>
</Grid>
<Button
sx = {classes(theme).loginButton}
type="submit" onClick={this.handleSubmit.bind(this)}
variant="contained"
color="primary"
>
Log In
</Button>
</Grid>
<Paper style = {{backgroundColor: "blue", borderRadius: "0em", display: "flex", flexDirection: "column"}} />
</Grid>
</div>
)}
}
export default styled(Login)({theme})
The styles file login.js
import commonstyles from "./common"
const styles = (theme) => ({
centerDivs: commonstyles(theme).centerDivs,
welcomeDiv: commonstyles(theme).welcomeDiv,
white: commonstyles(theme).white,
logo: {
margin: "auto",
marginTop: "2em",
marginBottom: "2em",
...commonstyles(theme).logo,
},
welcome: {
fontSize: "3em",
fontFamily: "Segoe UI",
color: "white",
marginBottom: "1em",
margin: theme.spacing(2),
textAlign: "center"
},
loginFields: {
...commonstyles(theme).textField,
width: "20em"
},
loginButton: {
...commonstyles(theme).button,
width: "10em"
},
myTextBox: {
...commonstyles(theme).textField,
// "& .MuiInputBase-root": {
// color: 'black',
// borderColor: "green"
// }
}
})
export default styles
the theme file theme.js
import { createTheme } from '#mui/material/styles';
const theme = createTheme({
palette: {
primary: {
main: "#065f92", // blue
},
secondary: {
main: "#F79007", // orange
},
error: {
main: "#d32f2f",
},
warning: {
main: "#ed6c02",
},
info: {
main: "#0288d1",
},
success: {
main: "#2e7d32",
},
},
spacing: (factor) => `${factor}rem`,
});
export default theme;
and finally the App.js file that pulls it all together:
import React from "react";
import { Provider } from 'react-redux'
import theme from './theme';
import { ThemeProvider } from '#mui/material/styles';
import "./App.css";
import store from "./app/store";
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import Login from "./containers/Login";
function App() {
return (
<ThemeProvider theme={theme}>
<Provider store={store}>
<div className="App" style={{maxHeight: "80%"}}>
<Router>
<Routes>
<Route path="/" element={<Login />} />
<Route path="/login" element={<Login />} /></Routes>
</Router>
<div style={{clear:"both", "height": "40px"}}></div>
</div>
</Provider>
</ThemeProvider>
);
}
export default App;

React.js Image Slider Back Button

I am fairly new to JavaScript and React, so I was hoping someone would be able to help me with something that seems fairly easy, I just don't fully grasp the concepts. I do not want to use ReactRouter, just manage it within the file.
I am creating a simple image slider using React and Material UI. However, I am having some difficulty with the functionality of the back button, preventing the app from crashing when going past the first image (into the negatives), and displaying the image number (ie: 3/5).
Here is my code:
import React, { useState } from "react";
import Button from "#material-ui/core/Button";
import MobileStepper from "#material-ui/core/MobileStepper";
import Paper from "#material-ui/core/Paper";
import KeyboardArrowRight from "#material-ui/icons/KeyboardArrowRight";
import Typography from "#material-ui/core/Typography";
import { useTheme } from "#material-ui/core/styles";
import KeyboardArrowLeft from "#material-ui/icons/KeyboardArrowLeft";
const myCollection = [
{
label: "First Picture",
imgPath:
"https://randompicturegenerator.com/img/dog-generator/g0ae914387a19ba58fc07fffe7f6952176159f445a3cd128c43ad59ae8b9baed35d8784cb3cdf4f4c16897571568d60c5_640.jpg",
},
{
label: "Second Picture",
imgPath:
"https://randompicturegenerator.com/img/dog-generator/g913a2b6f81253654df3b9e66abc189e6b966daf7a7a37b814b2336ab4459a832db90c8b923a5a8e28e63bb2fdd4496e1_640.jpg",
},
{
label: "Third Picture",
imgPath:
"https://randompicturegenerator.com/img/dog-generator/g5d33df79829d9cfbba39903471d1cd1bc2d6cdd243e222607e337d5575cb76ed10582deda8ed10bb0d1c3c43a6494f5a_640.jpg",
},
{
label: "Fourth Picture",
imgPath:
"https://randompicturegenerator.com/img/dog-generator/g446bd15f34f6fcb35272fa878493a90e9600b73e57f1f1dbca68ac22b9a1f780cb58c8a940d5727f930aa78d7b537b82_640.jpg",
},
{
label: "Fifth Picture",
imgPath:
"https://randompicturegenerator.com/img/dog-generator/g2efe8ff4951d16cc2d042d3714796204a975eb2c32fc5ee60d08956a729b7d5114b32cb0db6a5ba2e6d2948b8a6a0320_640.jpg",
},
];
const App = () => {
const CollectionSize = myCollection.length;
const theme = useTheme();
const [index, setIndex] = useState(0);
const goToNextPicture = () => {
setIndex((prevIndex) => prevIndex + 1);
};
const goToPrevPicture = () => {
setIndex((prevIndex) => prevIndex - 1);
};
return (
<>
<div style={{ marginLeft: "40%" }}>
<h2>Mans Best-Friend</h2>
<div style={{ maxWidth: 400, flexGrow: 1 }}>
<Paper
square
elevation={0}
style={{
height: 50,
display: "flex",
paddingLeft: theme.spacing(4),
backgroundColor: theme.palette.background.default,
alignItems: "center",
}}
>
<Typography>{myCollection[index].label}</Typography>
</Paper>
<img
src={myCollection[index].imgPath}
style={{
height: 255,
width: "100%",
maxWidth: 400,
display: "block",
overflow: "hidden",
}}
alt={myCollection[index].label}
/>
<MobileStepper
variant="text"
position="static"
index={index}
steps={CollectionSize}
nextButton={
<Button
size="small"
onClick={goToNextPicture}
disabled={index === CollectionSize - 1}
>
Next
{theme.direction !== "rtl" ? (
<KeyboardArrowRight />
) : (
<KeyboardArrowLeft />
)}
</Button>
}
/>
<MobileStepper
variant="text"
position="static"
index={index}
steps={CollectionSize}
backButton={
<Button
size="small"
onClick={goToPrevPicture}
disabled={index === CollectionSize + 1}
>
Back
{theme.direction !== "ltl" ? (
<KeyboardArrowRight />
) : (
<KeyboardArrowLeft />
)}
</Button>
}
/>
</div>
</div>
</>
);
};
export default App;
Error I am getting in the console:
const goToNextPicture = () => {
index<{your_array}.length-1?
setIndex((prevIndex) => prevIndex + 1):setIndex(0);
};
const goToPrevPicture = () => {
index>0
setIndex((prevIndex) => prevIndex - 1):setIndex(arr.length-1);
};
enter code here

Categories

Resources