SearchBox

mail@pastecode.io avatar
unknown
javascript
2 years ago
2.8 kB
4
Indexable
Never
import { useAuth0 } from '@auth0/auth0-react';
import { Search } from '@mui/icons-material';
import {
    FilledInput,
    FormControl,
    IconButton,
    InputAdornment,
    InputLabel,
} from '@mui/material';
import { useRef, useState } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';

export const SearchBox = () => {
    const navigate = useNavigate();
    const { user } = useAuth0();
    const roles = user ? user['https://bikeloop.no/roles'] ?? [] : [];
    const hasCorrectRole = roles.some(
        (user: string) => user === 'Admin' || 'Employee' || 'ServiceWorker'
    );
    const searchQueryRef = useRef<HTMLInputElement>();
    const [searchParams] = useSearchParams();
    const [searchString, setSearchString] = useState(searchParams.get('query'));

    const handleSearch = () => {
        const searchQuery = searchQueryRef.current?.value;

        if (searchQuery && searchQuery !== '') {
            const newSearchParams = new URLSearchParams({ query: searchQuery });
            navigate(`/users?${newSearchParams.toString()}`);
            setSearchString(null);
        }
    };

    return (
        <div>
            {hasCorrectRole ? (
                <FormControl
                    sx={{
                        m: 1,
                        width: '50ch',
                        maxWidth: '90%',
                        borderRadius: 2,
                    }}
                    variant="filled"
                >
                    <InputLabel htmlFor="search-input">
                        Search for user
                    </InputLabel>
                    <FilledInput
                        disableUnderline
                        sx={{ borderRadius: 1 }}
                        id="search-input"
                        type="text"
                        value={searchString}
                        onChange={(event) =>
                            setSearchString(event.target.value)
                        }
                        inputRef={searchQueryRef}
                        onKeyDown={(event) =>
                            event.key === 'Enter' ? handleSearch() : undefined
                        }
                        endAdornment={
                            <InputAdornment position="end">
                                <IconButton
                                    aria-label={'Search users'}
                                    onClick={handleSearch}
                                    edge="end"
                                >
                                    <Search />
                                </IconButton>
                            </InputAdornment>
                        }
                    />
                </FormControl>
            ) : null}
        </div>
    );
};