Home > Net >  Trying to show element based on user selection
Trying to show element based on user selection

Time:01-26

Here I have my div that contains Two Options ["Book" , "prices"] . My goal is when the user select the Book option it would show the element for the book , same thing for the price one too .

here is my code :

const BooksandPrices = props => {
    const option =["Book" , "Prices"]
    return (
        <div>
                    {option.map((option) => (
                        <div
                            className='bp'
                            onClick={(e) => {
                                {option == 'Book' && <PriceTable  />}
                                {option == 'Prices' && <BookTable  />}
                            }}
                        >
                            {option}
                            </div>
                    ))}
        </div>
    )
}

return (

<BooksandPrices />

)

CodePudding user response:

If my presumption is correct that and are the elements for each respective option, then you'll want to move them outside of the option.map and initialize a state variable to control which element is displayed

const BooksandPrices = props => {
    const [selectedOption, setSelectedOption] = useState();
    const option =["Book" , "Prices"]
    return (
        <div>
                    {option.map((option) => (
                        <div
                          className='bp'
                          onClick={() => setSelectedOption(option)}
                        >
                            {option}
                            </div>
                    ))}
                    {selectedOption == 'Book' && <PriceTable  />}
                    {selectedOption == 'Prices' && <BookTable  />}
        </div>
    )
}

return (

<BooksandPrices />

)

CodePudding user response:

React Hooks could solve this, you just need to add useState hook. Also keep in mind that you should to add key attribute when you loop through an array.

const BooksandPrices = props => {
        const option =["Book" , "Prices"];
        const [checkedOption, setCheckedOption] = useState("Book");
        return (
            <div>
                        {option.map((option, idx) => (
                            <div
                                className='bp'
                                onClick={()=>setCheckedOption(option)}
                                key={idx}
                            >
                            {option}
                           
                     
                                   
      
                                </div>
                        ))}
                         <div>
                            {checkedOption === 'Book' ? <BookTable  />:<PriceTable /> }
                            </div>
            </div>
        )
    }

  •  Tags:  
  • Related