Mr. Engineer
Mr. Engineer

Reputation: 375

How to identify which menu item has been clicked in React?

I'm new to React and I'm trying to implement small application which would load a different DOM based on what user clicks on the front page. Here is my App.js

import './App.css';
import MenuItems from './components/Navbar/MenuItems';
import ReactDOM from 'react-dom'
import React from 'react'

function App() {
  const apples = <h1 style={{textAlign: "center"}}>Apples</h1>;
  const oranges = <h1 style={{textAlign: "center"}}>Oranges</h1>;
  const bananas = <h1 style={{textAlign: "center"}}>Bananas</h1>;
  const click = () => {
    ReactDOM.render(
      apples,
      document.getElementById('root')
    )
  }
  let items = MenuItems.MenuItems.map((item,index) =>{
    console.log(item);
    return (<li onClick={click}>{item.title}</li>);
  })
  console.log(items)
  return (
    <div className="App">
      <div className="content">
        <h1>Fruit page</h1>
        {items}
      </div>
    </div>
    
  );
}

export default App;

Function "click" is called when user clicks any of menu items located in Menu.js

const MenuItems = [
    {
        title: 'Apples',
        url: '#',
        cName: 'nav-links'
    },
    {
        title: 'Oranges',
        url: '#',
        cName: 'nav-links'
    },
    {
        title: 'Bananas',
        url: '#',
        cName: 'nav-links'
    },
]
export default {MenuItems}

The problem is, I would like to render a specific const element based on what user clicks. Currently "apples" is loaded when ANY of the menu items is clicked. So, I will need to pass parameters to click function in order to identify which element to load, but how would I do that? Thanks in advance.

Upvotes: 1

Views: 1350

Answers (1)

Dennis Vash
Dennis Vash

Reputation: 53874

I'm guessing you trying to show the selected header, one possible approach might be:

const MenuItems = [
  {
    title: "Apples",
    url: "#",
    cName: "nav-links"
  },
  {
    title: "Oranges",
    url: "#",
    cName: "nav-links"
  },
  {
    title: "Bananas",
    url: "#",
    cName: "nav-links"
  }
];

function App() {
  const [selectedItem, setSelectedItem] = useState();

  return (
    <div className="App">
      <div className="content">
        <h1>Fruit page</h1>
        {MenuItems.map((item, index) => (
          <li
            key={index}
            onClick={() => setSelectedItem(item.title)}
            style={{ cursor: "pointer" }}
          >
            {item.title}
          </li>
        ))}
        {selectedItem && (
          <h1 style={{ textAlign: "center" }}>{selectedItem}</h1>
        )}
      </div>
    </div>
  );
}

Edit Select Example

Upvotes: 1

Related Questions