Sindhu
Sindhu

Reputation: 59

React Onclick display parent array

I am working on this React problem in which I want to display parent array from child array. For example, I have the Back Button and array Button

text: [ 
 title:"A1"
  list: [
 title: "A2"
  list: [ title: "A3"]
 title: "A2"
   ],
 title: "B1"
  list: [ title: "B2"],
 title: "C1"
  list: [ title: "C2"],
]

displayed as

Back Button
A1
B1
C1

and if a person clicks on "A1", it is displayed as

Back Button
A2
A2

if a person clicks on button,it should display the parent array like (I need to display this)

Back Button
A1
B1
C1

My_Code anyone know how to do this?

Upvotes: 2

Views: 90

Answers (1)

Drew Reese
Drew Reese

Reputation: 202836

You can maintain a simple stack of array elements you've clicked into, initialized to the root level's list array.

const [menuStack, setStack] = React.useState([data.list]);

const pushState = (list) => {
  list && setStack((stack) => [...stack, list]);
};
const popState = () => {
  menuStack.length > 1 && setStack((stack) => stack.slice(0, -1));
};

const top = menuStack[menuStack.length - 1];

If each level of depth has a list property then render a button or interactable element and push the new list onto the stack. Clicking the back button pops the last added list.

const data = {
  list: [
    {
      id: 0,
      title: "A1",
      list: [
        {
          id: 3,
          title: "A2",
          list: [
            {
              id: 7,
              title: "A3"
            }
          ]
        },
        {
          id: 4,
          title: "A2"
        }
      ]
    },
    {
      id: 1,
      title: "B1",
      list: [
        {
          id: 5,
          title: "B2"
        }
      ]
    },
    {
      id: 2,
      title: "C1",
      list: [
        {
          id: 6,
          title: "C2"
        }
      ]
    }
  ]
};

function App() {
  const [menuStack, setStack] = React.useState([data.list]);

  const pushState = (list) => {
    list && setStack((stack) => [...stack, list]);
  };
  const popState = () => {
    menuStack.length > 1 && setStack((stack) => stack.slice(0, -1));
  };

  const top = menuStack[menuStack.length - 1];

  return (
    <div className="App">
      <button onClick={popState}>Back</button>
      {top.map(({ id, title, list }) => (
        <div key={id}>
          {list ? (
            <button onClick={() => pushState(list)}>{title}</button>
          ) : (
            <div>{title}</div>
          )}
        </div>
      ))}
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  rootElement
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.1/umd/react-dom.production.min.js"></script>
<div id="root" />

Upvotes: 1

Related Questions