Home > Software engineering >  Conditional rendering inside map function ReactJs
Conditional rendering inside map function ReactJs

Time:07-03

I know there's similar thread already but i'm a total newbie and i can't work it. I'm not able include conditional rendering after my map function, do i need some sortf of HTML-tag inbetween?

     const renderTableData = () => { 
    let id = 1;
    const activeButton = () => { 
    
    }
    return (
      <tr>
        {days.map((val) => (
            <td>
                 {timeSlot.map((n, i) => ( 
                    
                //     if(freeSlotsList.includes(id)){     THIS CODE SNIPPET
               //         return (<h1>Testing</h1>           DON'T WORK
              //          )}
                    
                 
              <button id={id  } className={activeButton}> {n} {id}</button> 
                 ))}
            </td>
        ))}
      </tr>
    );
  };

EDIT:

i can't seem to access my freeSlotsList, it looks like this

const [freeSlotsList, setFreeSlotsList] = useState([])

useEffect(() => {
Axios.post('http://localhost:3001/api/get/week1/ex').then((response) => {
    setFreeSlotsList(response.data)

    
  })
}, [])
  

CodePudding user response:

Try this, You need to wrap your code into {} if you want to write js code. As () will simply return that as jsx.

const renderTableData = () => { 
let id = 1;
const activeButton = () => { 

}
return (
  <tr>
    {days.map((val) => (
        <td>
             {timeSlot.map((n, i) => {
                
                 if(freeSlotsList.includes(id)){     
                    return (<h1>Testing</h1>         
                    )}
                
             
          return <button id={id  } className={activeButton}> {n} {id}</button> 
             )}}
        </td>
    ))}
  </tr>
);
};
  • Related