I have given a code to implement music player using context.
Below is the source code:
import React from 'react';
import {
BarSongTitle,
BottomBar,
Button,
PlayList,
Song,
SongTitle,
} from './styles.js';
import { songList } from './constants.js';
const buttonLabels = ['Not replaying', 'Replaying all', 'Replaying one'];
const PlayerProvider = ({ children }) => {
return children;
};
const usePlayerContext = () => {};
const ControlBar = () => {
const title = 'test - song';
return (
<BottomBar>
<BarSongTitle data-testid="barTitle">{title}</BarSongTitle>
<div>
<Button data-testid="previousButton">Previous</Button>
<Button data-testid="nextButton">Next</Button>
<Button data-testid="currentModeButton">{'replay mode'}</Button>
</div>
</BottomBar>
);
};
const Songs = () => {
const[currentSong, setCurrSongSel] = React.useState('');
return (
<PlayList>
{songList.map(({ title, author, id }) => (
<Song key={id} onClick={()=> setCurrSongSel(id)}>
<SongTitle data-testid={id} active={currentSong === id ? true : false}>
{title}
</SongTitle>
<p>{author}</p>
</Song>
))}
</PlayList>
);
};
export { PlayerProvider, Songs, ControlBar };
I need to pass the data of currentSong from Songs component to ControlBar component using context (PlayerProvider or usePlayerContext). Can someone know how?
This is the code for App.js(we can’t make any change to that):
<PlayerProvider>
<main data-test-id="mainPart">
<Songs/>
<ControlBar/>
</main>
</PlayerProvider>
I am new to hooks and context concept, so don’t know where to go from here.
2
Answers
you can initialized context value in PlayerProvider and pass context value in usePlayerContext. I hope this useful for you.
You can initialized value in PlayerProvider
To pass the data of currentSong from the Songs component to the ControlBar component using context, you need to create a context using
React.createContext()
and provide the context value usingPlayerProvider
. Then you can consume the context value using theusePlayerContext
hook in both the Songs and ControlBar components. Here’s how you can do it:PlayerContext
.PlayerProvider
to provide thePlayerContext
with a value.usePlayerContext
hook to consume thePlayerContext
.Songs
component to use theusePlayerContext
hook.ControlBar
component to use theusePlayerContext
hook.With these modifications, the currentSong state will be shared between the Songs and ControlBar components using the context. When you click on a song in the Songs component, the title will be updated in the ControlBar component accordingly.