简体   繁体   中英

How to set the first value in a select dropdown to as a default react

I have a react program that displays a table based on values of a dropdown. I want the program to display the table by default based on the first value in the dropdown.

The first value in the dropdown is very different from the value made as default, and the dropdown values are always changing. So the data can be misleading when it loads for the first time.

here is a snippet of my code with a little description within. Thanks.

const CompletenessApp = () => {
    const [completeness, setcompleteness] = useState([]);
    const [loading, setloading] = useState(false);
    const [valueSelected, setValueSelected] = useState({value:'all'});
    const [periodSelected, setPeriodSelected] = useState({value:'20200702'}); // the default value that is used to filter the data.
    const valid = [
        {id:"all", variable:"all"},{id:"true", variable:"true"}, {id:"false", variable:"false"}, {id:"null", variable:"null"},
    ];
    useEffect(() => {
        const fetchData = async () => {
            try{
                const res = await axios.get('http://localhost:8000/api/completeness/');
                setcompleteness(res.data);
                setloading(true);
            } catch (e) {
                console.log(e)
            }
        }
        fetchData();
    }, []);
    // when the page loads for the first time it filters the data based on the period value set in the state. I want the data to be filtered based on the first value in the dropdown instead, the first value in the dropdown is different from the default value set.
    const handlePeriodChange = e => {
        setPeriodSelected({value : e.target.value})
    }

    const handleValueChange = e => {
        let boolvalue = Boolean
        e.target.value === 'true'? boolvalue = true:
        e.target.value === 'false'? boolvalue = false:
        e.target.value === 'all'? boolvalue = 'all':
        boolvalue=null
        setValueSelected({value : boolvalue})
    }
    //filtered data to be displayed
    const filteredCompleteness = completeness.filter(
        completedata=> (completedata.period === periodSelected.value)
        &&(valueSelected.value !== 'all'?completedata.complete === valueSelected.value:{}))


    return(
        <div>
            <div className="selection-row">
                <div className="stats-columns">
                    <div className="stats-label">Period</div>
                    //the relevant dropdown is here
                    <select onChange={e => handlePeriodChange(e)}>
                        {Array.from(new Set(completeness.map(obj => obj.period)))
                            .sort().reverse()
                            .map(period => {
                            return <option value={period}>{period}</option>
                        })}
                    </select>
                </div>
                <div className="stats-columns">
                    <div className="stats-label">Value</div>
                    <select onChange={e => handleValueChange(e)}>
                        {valid.map((obj) => {
                            return <option value={obj.id}>{obj.variable}</option>
                        })
                        }
                    </select>
                </div>
            </div>
            <hr></hr>
            <div className="results-table">
                 //table is displayed here
            </div>
        </div>
    );
}


export default CompletenessApp;
// above return
const options = Array.from(new Set(completeness.map((obj) => obj.period)))
  .sort()
  .reverse()
  .map((period) => {
    return {
      value: period,
      label: period,
    };
  });


// in jsx

<select defaultValue={options[0].value} onChange={e => handlePeriodChange(e)}>
 {
  options.map((obj) => {
    return <option value={obj.value}>{obj.label}</option>;
  })
}
</select>

Try this and let me know.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM