Home > database >  React - trouble rendering <div> in array.map()
React - trouble rendering <div> in array.map()

Time:08-16

I've been trying to figure this out for a couple days & haven't had any luck after reviewing similar questions.

The page loads the first menu item. But, when you click on it, only console.log(page) goes off & the following <div>{page}</div> don't appear on the page.

import React from 'react';
import { Component } from 'react';
import ReactDOM from 'react-dom/client';
import { Collapse } from 'react-bootstrap';


class Menu extends Component {
  constructor(props) {
    super(props);
    this.state = {
      pages: ['a', 'b', 'c'],
      selectedPage: 'a',
      isOpen: false,
    };
  }

  toggle() {
    this.setState({isOpen: !this.state.isOpen})
  }

  selectPage(page) {
    this.setState({ selectedPage: {page}})
  }

  listPages = (
    () => {
      let p;
      
      p = this.state.pages.filter( page => page !== this.state.selectedPage);

      /*
      nesting <div> in <>{}</> didn't fix
      */
      p.map((page, index) => {
          console.log(page)
          return (
            <div 
              className={page   ' menu-item'}
              onClick={() => {this.selectPage(page); this.toggle();}}
              key={index   1}
            >
              {page}
            </div>
          )
        }  
      );
    } 
  )


  render() {

    return(
      <div className='menu'>
        <div 
          className={ this.state.selectedPage   ' menu-item'}
          onClick={() => { this.toggle()} }
          key={1}
        >
          {this.state.selectedPage}
        </div>
        <Collapse in={this.state.isOpen}>
          <>
          {this.listPages()}
          </>
        </Collapse>
      </div>
      
    )
  }

}

CodePudding user response:

the function listPages is being executed but it doesn't return anything to show, what you need to do is add a return to your function for the map like this:

listPages = () => {
      let p;
      
      p = this.state.pages.filter( page => page !== this.state.selectedPage);

      /*
      nesting <div> in <>{}</> didn't fix
      */
      return p.map((page, index) => {
          console.log(page)
          return (
            <div 
              className={page   ' menu-item'}
              onClick={() => {this.selectPage(page); this.toggle();}}
              key={index   1}
            >
              {page}
            </div>
          )
        }  
      );
    } 

  • Related