0

I have a project of mine where a click should happen (click first one from collapsed list item), but it should happen automatically without user taking mouse on it(cursor) and clicking it.

that list item collapse comes from material ui.

any idea is appreciated.

my code to try : https://codesandbox.io/s/material-ui-nested-list-forked-2sqtum?file=/src/components/NestedItem/index.js

import React, { useState } from "react";
import List from "@material-ui/core/List";
import ListItem from "@material-ui/core/ListItem";
import ListItemText from "@material-ui/core/ListItemText";
import Collapse from "@material-ui/core/Collapse";

const NestedItem = ({ children }) => {
  const [isOpen, setIsOpen] = useState(false);

  const handleIsOpen = () => {
    setIsOpen((prev) => !prev);
  };
  const data = ["Someshit inside Collapse", "Someshit inside Collapse 2"];

  return (
    <List>
      <ListItem button onClick={handleIsOpen}>
        <ListItemText primary={children} />
      </ListItem>
      <Collapse in={isOpen}>
        {data.map((el) => (
          <List>
            <ListItem button>
              <ListItemText primary={el} />
            </ListItem>{" "}
          </List>
        ))}
        <List></List>
      </Collapse>
    </List>
  );
};

export default NestedItem;

this should be clicked ('Someshit inside Collapse') when user opens the page and just once, it could print console.log('text Someshit inside Collapse is clicked'):

enter image description here

walee
  • 575
  • 4
  • 16

2 Answers2

0

Add an ID to the element you want to click, then you can do something like

document.getElementById("elementYouWantToClick").click();
0

This answer could be what you are looking for: Simulate click event on react element

tldr: You can't just fire .click() on the element, you have to simulate mousedown and mouseup events.

borderr
  • 165
  • 4
  • i just one first item to be clicked if there is any – walee Nov 17 '22 at 21:35
  • You can select the first button from your list by using `yourListElement.firstChild` – borderr Nov 17 '22 at 21:38
  • possible working code ? – walee Nov 17 '22 at 21:55
  • You will need to uniquely identify your list, with an id for example, and then you can use `document.getElementById('your-list-id-here').firstChild­` to get the first button of the list, then you can dispatch the virtual click events on that element to "click" it. – borderr Nov 17 '22 at 22:06