`The chosen item is not appearing in view`

Having trouble displaying the skill label on the value.map function. I've tried every possible solution I can think of, including adding text inside the span but outside value.map. The text shows up, but the selected item does not. I even console log it and it shows up. Any assistance would be greatly appreciated.

import React from 'react';
import style from './index.module.css'
import App from './App'
import { useState } from 'react';
import { useEffect } from 'react';
import { options } from './data';

 
const Skill =()=>{
    const [isOpen, setIsOpen]=useState(false);
    const [highlightedIndex, setHighlightedIndex]=useState(0);
    const [value, setValue] = useState([options[0]]);
    const arrLenght = value.length;

    

    const clearOption=()=>{
       onChange([]) ;
    }

    const isOptionSelected = (option)=>{
         return  arrLenght > 1 ? value.includes(option)
         :  option === value;
    }

    const onChange =(o)=>{
        setValue([...value, o]);
    }

   useEffect (()=>{
     if (isOpen) setHighlightedIndex(0);
   },[isOpen])



    const selectOption= (option)=>{

        if(value.includes(option)){
            onChange(value.filter(o => o !== option))
        }else {
            onChange( option)
        }
    }
    
return (
    
 <div  onBlur={()=>setIsOpen(false) } 
     onClick={()=>setIsOpen(prev=> !prev)} tabIndex={0} 
      className={style.container} >
         
     <span className={style.value}> 
         
     {

        value.map((skill)=>{
            <button key={skill.value} onClick={e => {e.stopPropagation(); selectOption(skill)}} className={style['option-badge']}>     
                   {skill.label }
                 {console.log(skill)}
                <span className={style['remove-btn']}>&times;</span>
            </button>

        })  
        
 
    }
        
     
     </span>

     <button onClick={e =>{e.stopPropagation();  clearOption();} } 

         className={style['clear-btn']}>&times;</button>

     <div className={style.divider}></div>
     <div className={style.caret}></div>
     <ul className={`${style.options} ${isOpen ? style.show: ''}`}>
         
         {options.map((option, index)=>(

             <li  onClick={(e)=>{
                 e.stopPropagation();
                 selectOption(option);
                 setIsOpen(false);
                 onChange(option);
             }

             } key={option.value} 
             onMouseEnter={()=> setHighlightedIndex(index)}
             className={`${style.option}  ${isOptionSelected(option.label) ? style.selected : style.unselect}
             ${index === highlightedIndex ? style.highlighted: ''}`}>
                 {option.label}
             </li>
                 )
         )}
     </ul>
   
</div>
   )
}
 
export default Skill;

This is data.jsx that hold the options to be selected

export const options =[
    {label: 'first', value:1},
    {label: 'second', value:2},
    {label: 'third', value:3},
    {label: 'fouth', value:4},
    {label: 'fifth', value:5},
    {label: 'sixth', value:6}
  ];

Answer №1

Your brackets are just a bit off. In JSX, a map function returns HTML, and you can easily do it in a single line like this

=> (<html></html>)
. With that in mind, try something similar to this for it to work properly now.

 {value.map((skill) => (
          <button
            key={skill.value}
            onClick={(e) => {
              e.stopPropagation();
              selectOption(skill);
            }}
          >
            {skill.label}
            {console.log(skill)}
            <span>&times;</span>
          </button>
        ))}

Answer №2

Don't forget to include the return statement when using map with JSX.

value.map(skill => {
    return ( // Make sure you have this return statement.
        <button
            key={skill.value}
            onClick={e => {
                e.stopPropagation();
                selectOption(skill);
            }}
            className={style['option-badge']}
        >
            {skill.label}
            {console.log(skill)}
            <span className={style['remove-btn']}>&times;</span>
        </button>
    );
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Modifying audio output in a React element

I am trying to incorporate background music into my React app using TypeScript. However, I am encountering an issue where changing the music in the parent component does not affect the sound playing in the child node. import React from 'react'; ...

Customizable Button component featuring background image options

Need help with creating a versatile Button component in React that can easily accommodate different sizes and shapes of background images? This is how my current implementation looks like - Button.js const Button = ({ url }) => { const inl ...

Deactivating toolbar in material table in ReactJS while maintaining default functionalities

https://i.sstatic.net/XrA3I.pngHow can I remove the toolbar to eliminate the blank space between the table and button without disabling the add new row functionality? <MaterialTable title=" " options={{ ...

What is the trick to displaying Bootstrap 5 dropdown arrows when the button label is lengthy?

Within a fixed-width element, I have a Bootstrap dropdown which causes the arrow to disappear when the button text is too long. Is there a way to trim the text while still displaying the arrow, similar to this image: https://i.sstatic.net/jHp5R.png .ou ...

Tips for adding a new value to an array of objects in React

As I navigate my way through the world of React as a newcomer, I've encountered a challenge that I need some advice on. I am attempting to add a new key and value to an array of objects, but I'm struggling to accomplish this task. Can anyone prov ...

I am currently utilizing react-admin, however, I am encountering an issue with the heavy build causing errors

Currently, I am working on developing the frontend using react-admin. Initially, I intended to utilize NextJS and found a helpful reference article. Reference: When attempting to run next dev, everything worked smoothly without any errors. However, when ...

Reacting to the surprise of TS/JS async function behaving differently than anticipated

It appears that I'm facing a challenge with the small method; not sure if my brain is refusing to cooperate or what's going on. async fetchContacts() { await this.http.get('http://localhost:3000/contacts') .subscribe(res =& ...

The issue with updating the JSON data in VueJS when using draggable/sortable functionality

Hey everyone, I'm currently utilizing this library for sorting elements. I have a simple sortable setup where I'm trying to rearrange a three-element array by dragging. I can successfully change the positions, but the issue arises when my JSON ar ...

There seems to be an issue with the CSS file linking properly within an Express application

Every time I run my app.js file, the index.html file is displayed. However, when I inspect the page, I notice that the CSS changes are not taking effect. Strangely, if I open the HTML file using a live server, the CSS changes are visible. Can someone exp ...

What are the steps to kick off my React App once I've cloned it?

Currently grappling with deploying my app using Netlify, I encountered an issue after cloning the app onto my new computer. > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8afee5eee5e6e3f9fefcb8cabba4baa4ba">[email  ...

Experience a unique double scrolling effect using the react-spring parallax and react-three-fiber Canvas components

My goal is to create a scrolling box with a parallax effect, but I'm facing an issue where it won't bind with the Canvas element, even when both are included under the same div. In the screenshot provided, you can see div1 and div2 each having t ...

Utilizing unique layouts for specific views in sails.js and angular.js

I am currently working on a Sails.js + Angular.js project with a single layout. However, I have come across different HTML files that have a completely different layout compared to the one I am using. The layout file I am currently using is the default la ...

The table value is only updated once with the onclick event, but the updated value is not displayed when the event is clicked again

I am facing an issue with updating names in a table through a modal edit form. The first name update works perfectly, but the second update does not reflect in the table. I want every change made in the modal edit form to be instantly displayed in the tabl ...

"Converting Text from a Streamed XML-Like File into CSV: A Step-by-Step Guide

I have log files that contain C++ namespace artifacts (indicated by the double colons ::) and XML content embedded within them. After loading and displaying the logs in a browser application, the content has been separated from the Unix timestamps like so: ...

Filtering HTML with HtmlAgilityPack using custom queries

I am faced with a block of two HTML elements in this format: <div class="a-row"> <a class="a-size-small a-link-normal a-text-normal" href="/Chemical-Guys-CWS-107-Extreme-Synthetic/dp/B003U4P3U0/ref=sr_1_1_sns?s=automotive&amp;ie=UTF8& ...

Ways to retrieve every element inside a specific div container

Is there a way to select all elements inside a div except for specific ones? For example, consider the following structure: <div id="abc"> <div class="def"> sagar patil</div> <div class="pqr"> patil</div& ...

Automatically bring in functions in JavaScript without explicitly declaring them

I am working with 2 files. //main.js const one = (text) => { return text; } const two = (text) => { return text + " is here"; } module.exports = [ one, two ] //app.js const data = require("./main.js"); console.log(data.one("exampl ...

What is the best way to apply various styles to a single CSS class?

I'm in the process of implementing a dark mode feature on my website, and I want to do it without using any boilerplate code. My plan is to create a .darkmode class in CSS, apply styles to it, and have JavaScript add the darkmode class to the <bod ...

Is there a way to tally ng-required errors specifically for sets of radio buttons?

Currently, I am working on a form in AngularJS that includes groups of radio buttons. One of my goals is to provide users with an error count for the form. However, I have encountered a peculiar issue: After implementing this code to keep track of errors ...

I'm currently working on incorporating a rating system into my Vue.js project, but I am struggling to successfully pass the rating values

After carefully reviewing the documentation, I implemented the code below. While I am successfully retrieving data for enquiryDesc, I am encountering null values for rating. Despite trying various troubleshooting steps, the issue with null values persists. ...