Reputation: 1
Hi I'm fairly new to React and I am trying to add new items to an array which are then displayed when a button is pressed.
A new title will be added at the bottom with the name that's inputted in the textbox.
Here is my code:
import React, { useState } from "react";
import "./App.css";
import { Container, Button, Input } from "reactstrap";
function Row(props) {
return (
<li class="columnBox">
{props.title}
</li>
);
}
export default function App() {
const rows = [
{ title: "title 1"},
{ title: "title 2"},
{ title: "title 3"}
];
return (
<div className="App">
<h1>Add new titles</h1>
<form onSubmit={() => {
event.preventDefault();
rows.push({ title: "newRow"})
}}>
<Input type="text" name="email" id="newRow" placeholder="" />
<Button type="submit">add</Button>
</form>
<ul>
{rows.map((row) => (
<Row title={row.title} />
))}
</ul>
</div>
);
}
Upvotes: 0
Views: 62
Reputation: 457
you can use useState and update the state
import React, { useState } from "react";
import "./App.css";
import { Container, Button, Input } from "reactstrap";
export default function App() {
const [rows, setRows] = useState([
{ title: "title 1"},
{ title: "title 2"},
{ title: "title 3"}
]);
return (
<div className="App">
<h1>Add new titles</h1>
<form onSubmit={() => {
event.preventDefault();
setRows([
...rows,
{title: "newRow"}
])
}}>
<Input type="text" name="email" id="newRow" placeholder="" />
<Button type="submit">add</Button>
</form>
<ul>
{rows.map((row) => (
<Row title={row.title} />
))}
</ul>
</div>
);
}
Upvotes: 0
Reputation: 1914
For this you have to use state
. React application will normaly rerender when there is a change in state
or prop
.
export default function App() {
const [rows, setRows] = useState([
{ title: "title 1"},
{ title: "title 2"},
{ title: "title 3"}
]);
return (
<div className="App">
<h1>Add new titles</h1>
<form onSubmit={() => {
event.preventDefault();
setRows([
...rows,
{title: "newRow"}
])
}}>
<Input type="text" name="email" id="newRow" placeholder="" />
<Button type="submit">add</Button>
</form>
<ul>
{rows.map((row) => (
<Row title={row.title} />
))}
</ul>
</div>
);
}
Upvotes: 1