so I currently have a header component in my react js website and I want to set the title of it to an element of an array, but I cant seem to figure out how. here is my code
import Header from './components/Header';
var shoppinglist = []
var currentitem = ""
const App = () => {
function getData(val){
console.warn(val.target.value)
currentitem = val.target.value;
}
function logData() {
shoppinglist.push(currentitem)
console.log(shoppinglist)
}
function deleteItem() {
shoppinglist.pop()
console.log(shoppinglist)
console.log(shoppinglist[0])
}
return (
<div className="Container">
<Header title = "grocery list" />
<input type="text" onChange={getData}></input>
<button onClick={logData}>add item to list</button>
<button onClick={deleteItem}>delete item</button>
<div className="listItems">
<Header title = {shoppinglist[0]} />
</div>
</div>
);
}
export default App;
how would i set the header title to shoppinglist[0]?
CodePudding user response:
You have to have React state in order to render your content - in your case title. You can read more in react.js
One way of achieving what you asked in question: https://codesandbox.io/s/competent-wildflower-uvusd?file=/App.js
import "./styles.css";
import React from "react";
export default function App() {
const [title, setTitle] = React.useState(null);
const [input, setInput] = React.useState(null);
function getData(val) {
console.warn(val.target.value);
setInput(val.target.value);
}
function deleteItem() {
setTitle(null);
}
return (
<div className="Container">
<input type="text" onChange={getData}></input>
<button onClick={() => setTitle(input)}>add item to list</button>
<button onClick={deleteItem}>delete item</button>
{title && (
<div>
<p>{title}</p>
</div>
)}
</div>
);
}
CodePudding user response:
If you want a dynamic component in react you have to use state-variables. Else React doesn't re-render your code. This could look like this with React Hooks:
import Header from './components/Header';
var currentitem = ""
const App = () => {
const [shoppinglist, setShoppinglist] = useState([]);
function getData(val){
console.warn(val.target.value)
currentitem = val.target.value;
}
function addItem() {
shoppinglist.push(currentitem)
setShoppinglist([...shoppinglist])
}
function deleteItem() {
shoppinglist.pop()
setShoppinglist([...shoppinglist])
}
return (
<div className="Container">
<Header title = "grocery list" />
<input type="text" onChange={getData}></input>
<button onClick={addItem}>add item to list</button>
<button onClick={deleteItem}>delete item</button>
<div className="listItems">
<Header title = {shoppinglist[0]} />
</div>
</div>
);
}
export default App;