React Basics: useState Hooks With Forms
SongList.js
import React, { useState } from 'react';
import uuid from 'uuid/v1';
//library for unique ids for React keys
import NewSongForm from './NewSongForm';
const SongList = () => {
const [songs, setSongs] = useState([
//put getter and setter into state
{ title: 'almost home', id: 1 },
{ title: 'memory gospel', id: 2 },
{ title: 'this wild darkness', id: 3 }
]);
const addSong = (title) => {
//spread current song list into setter,
//then add newly added song to setter
setSongs([...songs, { title, id: uuid() }]);
};
return (
<div className="song-list">
<ul>
{songs.map(song => {
//map a new array for display
//in a ul list
return ( <li key={song.id}>
{song.title}
</li> );
})}
</ul>
<NewSongForm addSong={addSong} />
//dont forget to add the prop
</div>
);
}
export default SongList;
NewSongForm.js
import React, { useState } from 'react';
const NewSongForm = ({ addSong }) => {
const [title, setTitle] = useState('');
// useState can be used multiple
//times for different data
const [artist, setArtist] = useState('');
const handleSubmit = (e) => {
e.preventDefault();
addSong(title);
setTitle('');
}
return (
<form onSubmit={handleSubmit}>
<label>Song name:/label>
<input type='text' value={title}
onChange={(e) =>
setTitle(e.target.value)} />
<input type='submit' value='add' />
</form>
);
}
export default NewSongForm;