Reactify

Setting Up Your Environment

If you haven’t set up a React project yet, you can use Create React App:

bashCopy codenpx create-react-app reactify
cd reactify

Step 2: Create Basic Components

We’ll create two main components: SongList and AddSong.

1. Create SongList.js

In the src folder, create a new file called SongList.js:

jsxCopy code// src/SongList.js
import React from 'react';

const SongList = ({ songs }) => {
  return (
    <ul>
      {songs.map((song, index) => (
        <li key={index}>{song}</li>
      ))}
    </ul>
  );
};

export default SongList;

2. Create AddSong.js

Now create another file called AddSong.js:

jsxCopy code// src/AddSong.js
import React, { useState } from 'react';

const AddSong = ({ onAdd }) => {
  const [inputValue, setInputValue] = useState('');

  const handleSubmit = (e) => {
    e.preventDefault();
    if (inputValue) {
      onAdd(inputValue);
      setInputValue('');
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      <input
        type="text"
        value={inputValue}
        onChange={(e) => setInputValue(e.target.value)}
        placeholder="Add a new song"
      />
      <button type="submit">Add</button>
    </form>
  );
};

export default AddSong;

Step 3: Main Application Component

Now, let’s tie everything together in App.js.

jsxCopy code// src/App.js
import React, { useState } from 'react';
import SongList from './SongList';
import AddSong from './AddSong';

const App = () => {
  const [songs, setSongs] = useState([]);

  const addSong = (song) => {
    setSongs([...songs, song]);
  };

  return (
    <div>
      <h1>My Playlist</h1>
      <AddSong onAdd={addSong} />
      <SongList songs={songs} />
    </div>
  );
};

export default App;

Step 4: Run Your Application

Now you can start your application. In your terminal, run:

bashCopy codenpm start

Step 5: Explore and Enhance

You now have a basic React application that allows you to add songs to a playlist. You can enhance it by adding features like:

  • Removing songs
  • Persisting the playlist to local storage
  • Adding additional song details (artist, album)

Summary

This tutorial walked you through creating a simple React application with a playlist feature. You learned how to manage state and create reusable components in React.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *