@mui/material#Autocomplete JavaScript Examples

The following examples show how to use @mui/material#Autocomplete. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MagnitudeAutocomplete.js    From admin-web with GNU Affero General Public License v3.0 6 votes vote down vote up
MagnitudeAutocomplete = props => {
  const { t, className, value, filterAttribute, onChange, options, label, getOptionLabel,
    inputValue, onInputChange, freeSolo, multiple, calculateMagnitude, placeholder, renderOption,
    autoFocus, autoSelect, variant, fullWidth, disabled } = props;
  const magnitude = calculateMagnitude === false ? 0 : Math.round(Math.log10(options.length) - 2);

  return <Autocomplete
    className={className}
    inputValue={inputValue}
    value={value}
    onChange={onChange}
    options={options || []}
    getOptionLabel={getOptionLabel || (o => o[filterAttribute] || '')}
    filterOptions={inputValue ? getAutocompleteOptions(filterAttribute, magnitude) : undefined}
    noOptionsText={inputValue && inputValue.length < magnitude ?
      t('Filter more precisely') + '...' : t('No options')}
    renderInput={(params) => (
      <TextField
        {...params}
        label={label || ''}
        placeholder={placeholder}
        autoFocus={autoFocus}
        onChange={onInputChange}
        variant={variant || 'outlined'}
      />
    )}
    renderOption={renderOption}
    freeSolo={freeSolo || false}
    multiple={multiple || false}
    autoSelect={autoSelect}
    fullWidth={fullWidth || false}
    autoHighlight
    disabled={disabled || false}
  />;
}
Example #2
Source File: index.js    From zoomkoding-gatsby-blog with BSD Zero Clause License 6 votes vote down vote up
function PostSearch({ posts }) {
  return (
    <Autocomplete
      disableClearable
      options={posts}
      onInputChange={(event, value, reason) => {
        if (reason === 'reset' && value) {
          const item = posts.find((item) => item.title === value);
          if (!item) return;
          navigate(item.slug);
        }
      }}
      filterOptions={(options, { inputValue }) =>
        options.filter(
          ({ title, categories }) => title.includes(inputValue) || categories.includes(inputValue),
        )
      }
      getOptionLabel={(option) => option.title}
      renderInput={(params) => (
        <div className="search-input-wrapper">
          <TextField
            {...params}
            className="search-input"
            variant="standard"
            size="medium"
            InputProps={{
              ...params.InputProps,
              endAdornment: <SearchIcon className="search-icon" />,
            }}
          />
        </div>
      )}
      noOptionsText="해당하는 글이 없습니다."
    />
  );
}
Example #3
Source File: LanguageDropdown.jsx    From Edlib with GNU General Public License v3.0 5 votes vote down vote up
LanguageDropdown = ({ language, setLanguage }) => {
    const { t } = useTranslation();
    const { edlibApi } = useConfigurationContext();

    const [open, setOpen] = React.useState(false);
    const { error, loading, response } = useFetchWithToken(
        edlibApi('/resources/v1/languages'),
        'GET',
        React.useMemo(() => ({}), []),
        true,
        true
    );

    return (
        <Autocomplete
            open={open}
            onOpen={() => {
                setOpen(true);
            }}
            onClose={() => {
                setOpen(false);
            }}
            isOptionEqualToValue={(option, value) => option === value}
            getOptionLabel={(option) => iso6393ToString(option)}
            options={response ? response.data : []}
            loading={loading}
            onChange={(e, v) => {
                setLanguage(v);
            }}
            value={language}
            renderInput={(params) => (
                <TextField
                    {...params}
                    fullWidth
                    label={_.capitalize(t('language'))}
                    variant="outlined"
                    InputProps={{
                        ...params.InputProps,
                        endAdornment: (
                            <>
                                {loading ? (
                                    <CircularProgress
                                        color="inherit"
                                        size={20}
                                    />
                                ) : null}
                                {params.InputProps.endAdornment}
                            </>
                        ),
                    }}
                />
            )}
        />
    );
}
Example #4
Source File: AsyncAutocomplete.jsx    From matx-react with MIT License 5 votes vote down vote up
AutoComplete = styled(Autocomplete)(() => ({ width: 300 }))
Example #5
Source File: AutocompleteCombo.jsx    From matx-react with MIT License 5 votes vote down vote up
AutoComplete = styled(Autocomplete)(() => ({
  width: 300,
  marginBottom: '16px',
}))
Example #6
Source File: BadgeAutocomplete.jsx    From matx-react with MIT License 5 votes vote down vote up
BadgeAutocomplete = () => {
  const theme = useTheme();

  return (
    <Box
      sx={{
        width: 500,
        '& > * + *': {
          marginTop: theme.spacing(3),
        },
      }}
    >
      <Autocomplete
        multiple
        id="tags-standard"
        options={top100Films}
        getOptionLabel={(option) => option.title}
        defaultValue={[top100Films[13]]}
        renderInput={(params) => (
          <TextField
            {...params}
            variant="standard"
            label="Multiple values"
            placeholder="Favorites"
            fullWidth
          />
        )}
      />
      <Autocomplete
        multiple
        id="tags-outlined"
        options={top100Films}
        getOptionLabel={(option) => option.title}
        defaultValue={[top100Films[13]]}
        filterSelectedOptions
        renderInput={(params) => (
          <TextField
            {...params}
            variant="outlined"
            label="filterSelectedOptions"
            placeholder="Favorites"
            fullWidth
          />
        )}
      />
      <Autocomplete
        multiple
        id="tags-filled"
        options={top100Films.map((option) => option.title)}
        defaultValue={[top100Films[13].title]}
        freeSolo
        renderTags={(value, getTagProps) =>
          value.map((option, index) => (
            <Chip variant="outlined" label={option} {...getTagProps({ index })} />
          ))
        }
        renderInput={(params) => (
          <TextField
            {...params}
            variant="filled"
            label="freeSolo"
            placeholder="Favorites"
            fullWidth
          />
        )}
      />
    </Box>
  );
}
Example #7
Source File: index.js    From fireact with MIT License 4 votes vote down vote up
Plans = () => {
    const title = 'Select a Plan';

    const countries = countryJSON.countries;

    const { userData, authUser } = useContext(AuthContext);
    const stripe = useStripe();
    const elements = useElements();
    const mountedRef = useRef(true);
    const { setBreadcrumb } = useContext(BreadcrumbContext);

    const CARD_ELEMENT_OPTIONS = {
        style: {
            base: {
              color: '#32325d',
              fontFamily: '"Helvetica Neue", Helvetica, sans-serif',
              fontSmoothing: 'antialiased',
              fontSize: '16px',
              '::placeholder': {
                color: '#aab7c4'
              }
            },
            invalid: {
              color: '#fa755a',
              iconColor: '#fa755a'
            }
        },
        hidePostalCode: true
    };

    const [loading, setLoading] = useState(true);
    const [processing, setProcessing] = useState(false);
    const [plans, setPlans] = useState([]);
    const [selectedPlan, setSelectedPlan] = useState({id: 0});
    const [cardError, setCardError] = useState(null);
    const [errorMessage, setErrorMessage] = useState(null);
    const [country, setCountry] = useState("");
    const [countryError, setCountryError] = useState(null);
    const [state, setState] = useState("");
    const [states, setStates] = useState([]);
    const [stateError, setStateError] = useState(null);

    useEffect(() => {
        setBreadcrumb([
            {
                to: "/",
                text: "Home",
                active: false
            },
            {
                to: "/account/"+userData.currentAccount.id+"/",
                text: userData.currentAccount.name,
                active: false
            },      
            {
                to: null,
                text: title,
                active: true
            }
        ]);
        setLoading(true);

        const plansQuery = FirebaseAuth.firestore().collection('plans').orderBy('price', 'asc');
        plansQuery.get().then(planSnapShots => {
            if (!mountedRef.current) return null
            let p = [];
            planSnapShots.forEach(doc => {
                p.push({
                    'id': doc.id,
                    'name': doc.data().name,
                    'price': doc.data().price,
                    'currency': doc.data().currency,
                    'paymentCycle': doc.data().paymentCycle,
                    'features': doc.data().features,
                    'stripePriceId': doc.data().stripePriceId,
                    'current': (userData.currentAccount.planId===doc.id)?true:false
                });
            });
            if(p.length > 0){
                const ascendingOrderPlans = p.sort((a, b) => parseFloat(a.price) - parseFloat(b.price));
                setPlans(ascendingOrderPlans);
            }
            setLoading(false);
        });
    },[userData, setBreadcrumb, title]);

    useEffect(() => {
        return () => { 
            mountedRef.current = false
        }
    },[]);

    const subscribe = async(event) => {
        event.preventDefault();
        setProcessing(true);
        setErrorMessage(null);

        let hasError = false;
        let paymentMethodId = '';

        if(selectedPlan.price !== 0){
            if(country === ''){
                setCountryError('Please select a country.');
                hasError = true;
            }

            if(state === '' && countries[country] && countries[country].states){
                setStateError('Please select a state.');
                hasError = true;
            }

            setCardError(null);

            if (!stripe || !elements) {
                // Stripe.js has not loaded yet. Make sure to disable
                // form submission until Stripe.js has loaded.
                return;
            }
    
            // Get a reference to a mounted CardElement. Elements knows how
            // to find your CardElement because there can only ever be one of
            // each type of element.
            const cardElement = elements.getElement(CardElement);
    
            // Use your card Element with other Stripe.js APIs
            const {error, paymentMethod} = await stripe.createPaymentMethod({
                type: 'card',
                card: cardElement
            });
    
            if (error) {
                setCardError(error.message);
                hasError = true;
            } else {
                paymentMethodId = paymentMethod.id;
            }
        }

        
        if(!hasError){
            const createSubscription = CloudFunctions.httpsCallable('createSubscription');
            createSubscription({
                planId: selectedPlan.id,
                accountId: userData.currentAccount.id,
                paymentMethodId: paymentMethodId,
                billing: {
                    country: country,
                    state: state
                }
            }).then(res => {
                // physical page load to reload the account data
                if (!mountedRef.current) return null
                document.location = '/account/'+userData.currentAccount.id+'/';
            }).catch(err => {
                if (!mountedRef.current) return null
                setProcessing(false);
                setErrorMessage(err.message);
            });
        }else{
            setProcessing(false);
        }
    }

    return (
        <>
        {(!loading)?(
            <>{(userData.currentAccount.owner === authUser.user.uid)?(
            <>{plans.length > 0 ? (
            <Paper>
                <Box p={3} style={{textAlign: 'center'}} >
                    <h2>{title}</h2>
                    <Grid container spacing={3}>
                        
                            <>
                            {plans.map((plan,i) => 
                                <Grid container item xs={12} md={4} key={i} >
                                    <Card style={{
                                        width: '100%',
                                        display: 'flex',
                                        flexDirection: 'column',
                                        paddingBottom: '20px',
                                    }}>
                                        <CardHeader title={plan.name} subheader={"$"+plan.price+"/"+plan.paymentCycle} />
                                        <CardContent>
                                            <Divider />
                                            <ul style={{listStyleType: 'none', paddingLeft: '0px'}}>
                                            {plan.features.map((feature, i) => 
                                                <li key={i}>
                                                    <i className="fa fa-check" style={{color: "#2e7d32"}} /> {feature}
                                                </li>
                                            )}
                                            </ul>
                                        </CardContent>
                                        <CardActions style={{
                                            marginTop: 'auto',
                                            justifyContent: 'center',
                                        }}>
                                            {plan.current?(
                                                <Button color="success" variant="contained" disabled={true}>Current Plan</Button>
                                            ):(
                                                <Button color="success" variant={(plan.id!==selectedPlan.id)?"outlined":"contained"} onClick={() => {
                                                    for(let i=0; i<plans.length; i++){
                                                        if(plans[i].id === plan.id){
                                                            setSelectedPlan(plan);
                                                        }
                                                    }
                                                }}>{plan.id===selectedPlan.id && <><i className="fa fa-check" /> </>}{(plan.id!==selectedPlan.id)?"Select":"Selected"}</Button>    
                                            )}
                                        </CardActions>
                                    </Card>
                                </Grid>
                            )}
                            </>
                        
                    </Grid>
                    {selectedPlan.id !== 0 && selectedPlan.price > 0 && 
                        <div style={{justifyContent: 'center', marginTop: '50px'}}>
                            <h2>Billing Details</h2>
                            <Grid container spacing={3}>
                                <Grid container item xs={12}>
                                    <Card style={{
                                        width: '100%',
                                        paddingBottom: '20px',
                                    }}>
                                        <CardContent>
                                            <Container maxWidth="sm">
                                                <Stack spacing={3}>
                                                    {countryError !== null && 
                                                        <Alert severity="error" onClose={() => setCountryError(null)}>{countryError}</Alert>
                                                    }
                                                    <Autocomplete
                                                        value={(country !== '')?(countries.find(obj =>{
                                                            return obj.code === country
                                                        })):(null)}
                                                        options={countries}
                                                        autoHighlight
                                                        getOptionLabel={(option) => option.label}
                                                        renderOption={(props, option) => (
                                                            <Box component="li" sx={{ '& > img': { mr: 2, flexShrink: 0 } }} {...props}>
                                                                <img
                                                                    loading="lazy"
                                                                    width="20"
                                                                    src={`https://flagcdn.com/w20/${option.code.toLowerCase()}.png`}
                                                                    srcSet={`https://flagcdn.com/w40/${option.code.toLowerCase()}.png 2x`}
                                                                    alt=""
                                                                />
                                                                {option.label}
                                                            </Box>
                                                        )}
                                                        renderInput={(params) => (
                                                            <TextField
                                                                {...params}
                                                                label="Country"
                                                                inputProps={{
                                                                    ...params.inputProps,
                                                                    autoComplete: 'new-password',
                                                                }}
                                                            />
                                                        )}
                                                        onChange={(event, newValue) => {
                                                            if(newValue && newValue.code){
                                                                setCountry(newValue.code);
                                                                setState("");
                                                                if(newValue.states){
                                                                    setStates(newValue.states);
                                                                }else{
                                                                    setStates([]);
                                                                }
                                                                setCountryError(null);
                                                            }
                                                        }}
                                                    />
                                                    {states.length > 0 &&
                                                    <>
                                                        {stateError !== null && 
                                                            <Alert severity="error" onClose={() => setStateError(null)}>{stateError}</Alert>
                                                        }
                                                        <Autocomplete
                                                            value={(state !== '')?(states.find(obj =>{
                                                                return obj.code === state
                                                            })):(null)}
                                                            options={states}
                                                            autoHighlight
                                                            getOptionLabel={(option) => option.label}
                                                            renderOption={(props, option) => (
                                                                <Box component="li" {...props}>
                                                                    {option.label}
                                                                </Box>
                                                            )}
                                                            renderInput={(params) => (
                                                                <TextField
                                                                    {...params}
                                                                    label="State"
                                                                    inputProps={{
                                                                        ...params.inputProps,
                                                                        autoComplete: 'new-password',
                                                                    }}
                                                                />
                                                            )}
                                                            onChange={(event, newValue) => {
                                                                if(newValue && newValue.code){
                                                                    setState(newValue.code);
                                                                    setStateError(null);
                                                                }
                                                                
                                                            }}
                                                        />
                                                    </>
                                                    }
                                                    {cardError !== null && 
                                                        <Alert severity="error" onClose={() => setCardError(null)}>{cardError}</Alert>
                                                    }
                                                    <div style={{position: "relative", minHeight: '56px', padding: '15px'}}>
                                                        <CardElement options={CARD_ELEMENT_OPTIONS}></CardElement>
                                                        <fieldset style={{
                                                            borderColor: 'rgba(0, 0, 0, 0.23)',
                                                            borderStyle: 'solid',
                                                            borderWidth: '1px',
                                                            borderRadius: '4px',
                                                            position: 'absolute',
                                                            top: '-5px',
                                                            left: '0',
                                                            right: '0',
                                                            bottom: '0',
                                                            margin: '0',
                                                            padding: '0 8px',
                                                            overflow: 'hidden',
                                                            pointerEvents: 'none'
                                                            
                                                        }}></fieldset>
                                                    </div>
                                                </Stack>
                                            </Container>
                                        </CardContent>
                                    </Card>
                                </Grid>
                            </Grid>
                        </div>
                    }
                    {selectedPlan.id!==0 &&
                        <div style={{marginTop: '50px'}}>
                            <Container maxWidth="sm">
                                <Stack spacing={3}>
                                {errorMessage !== null && 
                                    <Alert severity="error" onClose={() => setErrorMessage(null)}>{errorMessage}</Alert>
                                }
                                <Button color="success" size="large" variant="contained" disabled={selectedPlan.id===0||processing?true:false} onClick={e => {
                                    subscribe(e);
                                }}>{processing?(<><Loader /> Processing...</>):(<>Subscribe Now</>)}</Button>
                                </Stack>
                            </Container>
                        </div>
                    }
                </Box>
            </Paper>
            ):(
                <Alert severity="warning">No plan is found.</Alert>
            )}</>
            ):(
                <Alert severity="error" >Access Denied.</Alert>
            )}</>
        ):(
            <Loader text="loading plans..." />
        )}
        </>

    )
}
Example #8
Source File: LocationAutocomplete.jsx    From matx-react with MIT License 4 votes vote down vote up
export default function LocationAutocomplete() {
  const theme = useTheme();
  const [inputValue, setInputValue] = React.useState('');
  const [options, setOptions] = React.useState([]);
  const loaded = React.useRef(false);

  if (typeof window !== 'undefined' && !loaded.current) {
    if (!document.querySelector('#google-maps')) {
      loadScript(
        'https://maps.googleapis.com/maps/api/js?key=AIzaSyBwRp1e12ec1vOTtGiA4fcCt2sCUS78UYc&libraries=places',
        document.querySelector('head'),
        'google-maps'
      );
    }

    loaded.current = true;
  }

  const handleChange = (event) => {
    setInputValue(event.target.value);
  };

  const fetch = React.useMemo(
    () =>
      throttle((input, callback) => {
        autocompleteService.current.getPlacePredictions(input, callback);
      }, 200),
    []
  );

  React.useEffect(() => {
    let active = true;

    if (!autocompleteService.current && window.google) {
      autocompleteService.current = new window.google.maps.places.AutocompleteService();
    }
    if (!autocompleteService.current) {
      return undefined;
    }

    if (inputValue === '') {
      setOptions([]);
      return undefined;
    }

    fetch({ input: inputValue }, (results) => {
      if (active) {
        setOptions(results || []);
      }
    });

    return () => {
      active = false;
    };
  }, [inputValue, fetch]);

  return (
    <Autocomplete
      id="google-map-demo"
      style={{ width: 300 }}
      getOptionLabel={(option) => (typeof option === 'string' ? option : option.description)}
      filterOptions={(x) => x}
      options={options}
      autoComplete
      includeInputInList
      freeSolo
      disableOpenOnFocus
      renderInput={(params) => (
        <TextField
          {...params}
          label="Add a location"
          variant="outlined"
          fullWidth
          onChange={handleChange}
        />
      )}
      renderOption={(option) => {
        const matches = option.structured_formatting.main_text_matched_substrings;
        const parts = parse(
          option.structured_formatting.main_text,
          matches.map((match) => [match.offset, match.offset + match.length])
        );

        return (
          <Grid container alignItems="center">
            <Grid item>
              <LocationOnIcon
                sx={{
                  color: theme.palette.text.secondary,
                  marginRight: theme.spacing(2),
                }}
              />
            </Grid>
            <Grid item xs>
              {parts.map((part, index) => (
                <span
                  key={index}
                  style={{
                    fontWeight: part.highlight ? 700 : 400,
                  }}
                >
                  {part.text}
                </span>
              ))}

              <Typography variant="body2" color="textSecondary">
                {option.structured_formatting.secondary_text}
              </Typography>
            </Grid>
          </Grid>
        );
      }}
    />
  );
}