React Basics - useState Hook (With Forms)

 

React Basics: useState Hook With Forms

This is another youtuber that I follow who offers some really good lessons on a variety of programming languages, check him out: https://www.youtube.com/watch?v=R7T5GQLxRD4

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;



 
Link your website to this page! Copy and paste the URL below:
http://www.cfsnap.com/react/react-basics-usestate-hook-with-forms/