Controlling the state of a hyperlink through prop passing in React components

Still getting the hang of React, so bear with me if this explanation is a bit shaky. I'm in the process of creating a React project that allows users to search for tracks by artists using the Spotify API. The search results will display cards with artist information, and when a user clicks on a tag (which contains a URL to a song preview), I want to show an audio visualizer component that works with the audio analyzer node and audio tags.

I'm encountering two main issues:

1) I need to pass the clicked song preview URL from the href to the audio analyzer component as the audio source (similar to setting audio.src = preview_url). To solve this problem, I either need to a) update the state with the current clicked href or b) pass the preview URL as props to the audio visualizer component.

2) Upon clicking the tag, I want the ArtistCard component to disappear so that only the audio visualizer component is visible (hopefully easier than resolving the first issue).

Here's my code - apologies if it's a bit confusing. Feel free to ask for clarification if needed:

export default class ArtistCard extends Component {
constructor(props){
    super(props)

    this.state = {
        renderAudioAnalyzer: false,
        visibility: ''
    }
}

togglePreviewUrlState(){
    this.setState({ renderAudioAnalyzer: true })
    if(this.state.renderAudioAnalyzer){
        this.refs.artistCard.style.display = 'hidden'
        //this currently doesn't work yet...
        // style={{display: 'none'}} <--- do something like this?
    }
}



render() {
    let {tracks} = this.props
    if(!this.state.renderAudioAnalyzer){
        return (
            <div className="card col s3" id="artistCard">
                <div className="card-inner">
                    <div className="card-image">
                        <img alt="/logo.svg" className="Image" src={tracks.album.images[1].url}/>
                        <span className="card-title"></span>
                    </div>
                    <div className="card-content">
                        <p id="artistCardTrackName">{tracks.album.name}</p>
                    </div>
                    <div className="card-action">
                        <a
                            onClick={this.togglePreviewUrlState.bind(this)}
                            href={tracks.preview_url} //need to set this as state or pass as props?
                        >{tracks.name}</a>
                    </div>
                </div>
            </div>
        )
    }else{
        return(
            <div><AudioAnalyzer/></div>
        )
    }
}
}

And here is the audio visualizer component (still a work in progress but trying to figure out how to properly pass over the href):

export default class AudioAnalyzer extends Component {
  constructor(props){
    super(props)
  }

  render(){
    return (
      <div id="mp3_player">
        <div id="audio_box">
          <audio
            refs="audio"
            autoPlay="true"
            controls="true"
            src={this.props.tracks.preview_url} <--href needs to be passed to here some how?
          >
          </audio>
        </div>
        <canvas
          refs="analyser"
          id="analyser"></canvas>
      </div>
    )
  }
}

Answer №1

    this.setState({ showAudioAnalyzer: true })
if(this.state.showAudioAnalyzer){
    this.refs.artistCard.style.display = 'hidden'
    //this feature is currently not functional...
    // try something like style={{display: 'none'}} <--- similar to this?
}

setState operates asynchronously, so after updating state, it can't be assumed that the state will be immediately set and checked with if(this.state.showAudioAnalyzer)

The logic in the render function will hide the artist card every time a link is clicked. (remember to include e.preventDefault to prevent unwanted app re-rendering).

Also, remember to pass the song URL as a prop to AudioAnalyzer, which is relatively simple.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The behavior of the 'typeof null' function in JavaScript is not functioning

I have a collection of objects where each object contains a key and an array as a value. You can see what I mean in this image. Some of the arrays had less than 20 elements, so I wrote some code to pad them with zeros. The result of running my code can be ...

Tips for choosing a row in Ag-grid when initiating a drag operation

My grid is set up with only 1 column. Currently, I am facing an issue where if row dragging is enabled, I cannot select rows unless I manually bind a key to set supressRowDrag=true. This should be possible and straightforward since the row node is alread ...

Troubleshooting create-react-app: Resolving localhost connectivity issues

Recently, I created a new React app using create-react-app. Whenever I try to start the development server with npm start, the server initializes and displays this: https://i.stack.imgur.com/f8psM.png Previously, I was able to open http://localhost:3000 ...

Issue encountered while deploying Next.js application on vercel using the replaceAll function

Encountering an error during deployment of a next.js app to Vercel, although local builds are functioning normally. The issue seems to be related to the [replaceAll][1] function The error message received is as follows: Error occurred prerendering page &q ...

What is the best way to send data from a header component to a separate container component?

Utilizing React-router-dom, I am able to seamlessly switch between components in the following setup: <Router> <div> <Header /> <NavigationBar /> <Switch> <Route exact path ...

Extracting JSON data from Stripe results - A comprehensive guide

I'm having trouble displaying the 'amount_total' in an h1 tag from my Stripe JSON response. Every time I try, I encounter this error: TypeError: Cannot read property 'map' of undefined Here is a snippet of the Stripe JSON output: ...

Creating a navigation bar in React using react-scroll

Is anyone able to assist me with resolving the issue I am facing similar to what was discussed in React bootstrap navbar collapse not working? The problem is that although everything seems to be functioning properly, the navbar does not collapse when cli ...

The issue of validation not being triggered upon wrapping Antd Input and Form.Item components within another component

Incorporating custom localization support into Antd Form by wrapping the <Form.Item> and Input components in a separate TextBox component has been a challenge. However, validation does not seem to work properly when adding the custom component insi ...

What is the best method to incorporate a JavaScript object key's value into CSS styling?

I am currently working on a project in React where I'm iterating over an array of objects and displaying each object in its own card on the screen. Each object in the array has a unique hex color property, and my goal is to dynamically set the font co ...

What is causing the difficulty in accessing the 'query' feature within the API, and why is the question bank failing to display?

Just wanted to mention that I am still learning about class based components, setState, and other concepts in async JS like axios. Below is a very basic example of what I can currently do. This is App.js: import Questions from './components/Ques ...

You are unable to utilize global SCSS in Next.js as the Global CSS is restricted to being imported only from files within your Custom <App> component

After setting up node-sass in my next.js application, I attempted to include my global scss file using import '../styles/style.scss'; in the _app.js component, but encountered an error: The system is alerting that Global CSS cannot be imported fr ...

Include a button alongside the headers of the material table columns

I am looking to customize the material table headers by adding a button next to each column header, while still keeping the default features like sorting and drag-and-drop for column rearrangement. Currently, overriding the headers requires replacing the e ...

Unable to minimize or hide the ace editor widget with Cypress

Today marks the beginning of my journey into posting on this platform, and I am eager to get it right. In my current project using Cypress for writing integration tests, I encountered a challenge while attempting to click on an Ace editor widget within a ...

How can I make Material UI's grid spacing function properly in React?

I've been utilizing Material UI's Grid for my layout design. While the columns and rows are functioning properly, I've encountered an issue with the spacing attribute not working as expected. To import Grid, I have used the following code: ...

The Navigation Stops Working Following an Automated Redirect from a 404 Page to the Homepage with next/router and useEffect()

I encountered a problem with next/router. I created a '404 Page' and configured it to redirect clients back to the home page router.push('/') after 3 seconds. However, when clients return to the main page, they encounter a console error ...

SSL/HTTPS issues impacting Server-Sent Events (SSE)

Greetings, I am currently in the process of developing a React web application that is designed to receive SSE data from an Express server working with Nginx. SERVER.JS const express = require('express'); const bodyParser = require('body-p ...

Every day, I challenge myself to build my skills in react by completing various tasks. Currently, I am facing a particular task that has me stumped. Is there anyone out there who could offer

Objective:- Input: Ask user to enter a number On change: Calculate the square of the number entered by the user Display each calculation as a list in the Document Object Model (DOM) in real-time If Backspace is pressed: Delete the last calculated resul ...

Unable to assign resources to component without rendering aspect

For a specific screen, I have the requirement to assign a list of components (Call) to execute some logic without having to return JSX to render on this screen. An attempt was made using FlatList as shown below: (1) Within the renderless component (Call) ...

Navigating with React-router can sometimes cause confusion when trying

I'm having trouble with my outlet not working in react-router-dom. Everything was fine with my components until I added the Outlet, and now my navigation component isn't showing even though other components are rendering. import Home from ". ...

Combining Switch components with a universal NoMatch element in React Router Version 4

My application is currently divided into three main parts: Frontend Administration Error Each part, including Frontend, Administration, and Error, has its own unique styling. In addition, both the Frontend and Administration components have their own S ...