Home > Software design >  Select option from dropdown and display in box
Select option from dropdown and display in box

Time:11-22

I have a dropdown with values in it which when selected should display that item in the div named search_box. I know that the idea here should be to use hooks, something which I have done already but I cannot get the selected value to display instead of the Enter District text in the search_box. I tried console logging to see if the selected value was displaying or not but since it isn't, I'm pretty sure I have messed up somewhere.

Here is my code:

import React, { useState } from "react";
import './search.css';
import { IoMdArrowDropdown } from 'react-icons/io';
import { GoTriangleUp } from 'react-icons/go';
import data from '../../../../data.json';

const SearchBox = () => {
    const [open, setOpen] = useState(false);
    const [dropDownValue, setDropDownValue] = useState(null);

    const onSelect = (value) => {
        setDropDownValue(value);
        setOpen(!open);
    };

    return (
        <div className="box_district">
            <div className="district_caption">District</div>
            <div className="block_drop">
                <div className="district_dropdown">
                    <div className="search_box">            //search box
                        Enter District                      //This is where the value should get selected
                    </div>
                    <div className="drop_icon" onClick={() => setOpen(prev => !prev)}>
                        {open ? <GoTriangleUp size={"22px"} /> : <IoMdArrowDropdown size={"30px"} />}
                    </div>
                </div>
                <div className={open ? "open_options" : "options"}>
                    {data.map((countries) => <div className="select_options" onClick={val => onSelect(val)}>    //This is where the options get rendered
                        {countries.name}
                        {console.log(dropDownValue)}
                    </div>
                    )}
                </div>
            </div>
        </div>
    );
}

export default SearchBox;

enter image description here

The dropdown goes away as functioned as soon as I click on something but that's how far this works.

CodePudding user response:

There are some minor changes you have to do here is used:

<div className="search_box">
  {dropDownValue === null ? "Enter District" : dropDownValue}
</div>

and

<div className="select_options" onClick={() => onSelect(countries?.name)}>
                {countries.name}
                {console.log(dropDownValue)}
              </div>

 
  • Related