Last active
September 1, 2019 16:49
-
-
Save stacietaylorcima/a83e6b3c2400e5b0155351f4563a20d1 to your computer and use it in GitHub Desktop.
Add data to Firestore in React
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 } from 'react'; | |
import { withFirestore } from 'react-firestore'; | |
import Header from '../../Components/Header'; | |
import Footer from '../../Components/Footer'; | |
const AddItem = ({ firestore }) => { | |
const [name, setName] = useState(''); | |
// Send the new item to Firebase | |
const addItem = name => { | |
firestore.collection('items').add({ name }); | |
}; | |
// The state every time an event happens | |
const handleChange = event => { | |
setName(event.target.value); | |
}; | |
// Handle the click of the Add Item botton on the form | |
const handleSubmit = event => { | |
event.preventDefault(); | |
addItem(name); | |
}; | |
return ( | |
<main className="pageTwo"> | |
<Header /> | |
<form onSubmit={handleSubmit}> | |
<label> | |
Add Item: | |
<input value={name} type="text" id="name" onChange={handleChange} /> | |
</label> | |
<button onClick={handleSubmit}>Add item</button> | |
</form> | |
<Footer /> | |
</main> | |
); | |
}; | |
// Wrap this component in the higher order componenet withFirestore to directly access the database | |
export default withFirestore(AddItem); | |
``` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment