Home > database >  How to exchange / switch a prop on the click of a button in NextJS?
How to exchange / switch a prop on the click of a button in NextJS?

Time:08-07

I have a video player component in NextJs that is populated with video links through a {videoLink} prop:

 <ReactPlayer playing={true} controls={true} muted={true} loop={true} width="100" height="100" 
url={videoLinkDeep} poster="images/330163_C2B_Clean.png">  </ReactPlayer>

The data being passed into the component consists of several different possible link props such as {videoLinkLong} or {videoLinkShort}.

The preset {videoLinkDeep) portion of the URL is now supposed to be exchanged through another video link prop such as {videoLinkLong} on the click of a button. How can I achieve this given that I start with a:

   <button className="bg-black">Preview Length</button>

Only?

CodePudding user response:

First of all, use the useState hook for the url.

const defaultVideoLink = "Default Link";
const longVideoLink = "Long Link";
const shortVideoLink = "Short Link";
const [videoLink, setVideoLink] = useState(dafaultVideoLink);

Then, depending on how you want your UI to be, you can use setState to change the url. Lets say you use three different buttons,

<button onClick={() => setVideoLink(defaultVideoLink)}>View Default Video</button>
<button onClick={() => setVideoLink(longVideoLink)}>View Long Video</button>
<button onClick={() => setVideoLink(shortVideoLink)}>View Short Video</button>

Finally, your react player component will be as follows:

<ReactPlayer {...props} url={videoLink}></ReactPlayer>

You can even do a dropdown or a menu component for the UI using some libraries, but in any case, the logic will be same. Let me know if you need any further help!

CodePudding user response:

Use the hook useState.

Examples and documentation available: https://reactjs.org/docs/hooks-state.html

  • Related