Created
April 5, 2021 07:20
-
-
Save revuel/ce373a2fcaf5e96b1e5d3c812153e027 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useState, useEffect } from "react"; | |
export default function StackExample() { | |
const [myArray, setMyArray] = useState([]); | |
const addElement = () => { | |
var myArrayCopy = [...myArray]; | |
var newKey = myArray.length; | |
myArrayCopy.push({ | |
item: <input disabled type="button" key={newKey} value={newKey} /> | |
}); | |
setMyArray(myArrayCopy); | |
}; | |
const dropElement = () => { | |
var myArrayCopy = [...myArray]; | |
myArrayCopy.pop(); | |
setMyArray(myArrayCopy); | |
}; | |
useEffect(() => { | |
var initialArray = [ | |
{ item: <input disabled type="button" key="0" value="0" /> }, | |
{ item: <input disabled type="button" key="1" value="1" /> }]; | |
setMyArray(initialArray); | |
}, []); | |
return ( | |
<div> | |
<p>Stack: LIFO data structure example</p> | |
<hr /> | |
{myArray.map((o) => o.item)} | |
<hr /> | |
<input value="+" type="button" onClick={addElement} /> | |
<input value="-" type="button" onClick={dropElement} /> | |
<div>Number of items: {myArray.length}</div> | |
{myArray.length % 2 === 0 ? <p>even</p> : <p>odd</p>} | |
</div> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment