tbleckert / react-select-search

⚡️ Lightweight select component for React
https://react-select-search.com
MIT License
676 stars 147 forks source link

how to make select search as mandatory field? #19

Closed re5ive closed 6 years ago

re5ive commented 7 years ago

how do i make this field as mandatory? required

tbleckert commented 7 years ago

Hi! Sorry for a slow reply. You should use the component as a subcomponent in a main form component. That way you can keep track wether it has a value or not and if not, do something. You can for example render it with a wrapper that gets an error class if form is submitted without it having a value. I hope that's what you mean. A simple example:

import React from 'react';
import SelectSearch from 'react-select-search';

class Form extends React.Component {

    constructor(props) {
        super(props);

        this.state = {
            country: '',
            error: false
        };
    }

    validData() {
        return this.state.country.length;
    }

    onSubmit(e) {
        e.preventDefault();

        if (!this.validData()) {
            this.setState({error: true});
        } else {
            // Send data to server
        }
    }

    onChange(value) {
        this.setState({country: value});
    }

    render() {
        let selectClassName = 'input-wrapper';

        if (this.state.error) {
            selectClassName += ' error';
        }

        return (
            <form onSubmit={(e) => this.onSubmit(e)}>
                <div class={selectClassName}>
                    <SelectSearch onChange={(value) => this.onChange(value)} />
                </div>
            </form>
        );
    }

}