Skip to content

Instantly share code, notes, and snippets.

@stacietaylorcima
Last active September 1, 2019 16:49
Show Gist options
  • Save stacietaylorcima/a83e6b3c2400e5b0155351f4563a20d1 to your computer and use it in GitHub Desktop.
Save stacietaylorcima/a83e6b3c2400e5b0155351f4563a20d1 to your computer and use it in GitHub Desktop.
Add data to Firestore in React
```
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