I'm studying to become a Front-End Developer and now react is on the menu. I need to create a react-app that has a grocery list and a shopping cart. I can add items to the grocery list and eventually I can click on them to transfer them to the shopping cart.
The whole react tree-like experience is quite new and overwhelming. But my question is, I need to add the data that I get from an input field to a UL/LI.
I have a GroceryList component, an InputField component, a List component, and a ListItem component.
The code I have now for the InputField works kind of but it displays the information directly on the screen and not on submit.
The code is:
import React, { useState } from "react";
import { ReactDOM } from "react";
function InputField(props) {
return (
< div >
<form>
<input type="text" onChange={(event) => props.setGroceryName(event.target.value)} />
<button type="submit" >Add Groceries</button>
</form>
</div >
)
}
export default InputField
I defined the setGroceryName in the GroceryList component. Can someone help me with how I can change it so it makes a list in the List component? I'm really stuck and can't seem to find some good help. Or what do I need to do and where do I need to put it so it takes a ListItem and adds that to the List component.
Thanks in advance. If you guys need more info, let me know.
import React, { Component } from 'react'
export default class Test extends Component {
state = {
grocery: '',
groceryList: []
}
render() {
return (
<div>
<form>
<input type="text" onChange={(e) => this.setState({ grocery: e.target.value })} />
<button type="submit" onClick={e => this.setState({ groceryList: [...this.state.groceryList, this.state.grocery], grocery: '' })}>Add Groceries</button>
</form>
</div>
)
}
}
You need to setState for every time the text is changing for a new grocery item and when clicked on the button, add it to the groceryList array, and set the initial text to an empty array.