omar ba44
omar ba44

Reputation: 23

How to make a specific button disappear permanently on React.js?

I am trying to make a button disappear after clicking so that even if I go to a different component(different pages) it will stay that way.

Here is the code:

<Button
  className="but"
  variant="primary"
  onClick={(e) => {
    const tr = {
      id: info.track.track_id,
      trackName: info.track.track_name,
      artistName: info.track.artist_name,
    };

    fetch('http://localhost:8000/blogs', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(tr),
    }).then(() => {
      console.log('blog added');
    });
  }}
  style={{ marginLeft: '6px' }}
>
  Mark
</Button>;

Upvotes: 0

Views: 3970

Answers (4)

fortunee
fortunee

Reputation: 4332

Since the Button is being rendered within a map, you can create a custom button component from your existing button that manages the hide state and returns the actual Button or null.

Custom button should look something like this:

const CustomButton = ({ info }) => {
  const [hide, setHide] = useState(false);

  return hide ? (
    <Button
      className="but"
      variant="primary"
      onClick={(e) => {
        const tr = {
          id: info.track.track_id,
          trackName: info.track.track_name,
          artistName: info.track.artist_name,
        };

        fetch('http://localhost:8000/blogs', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(tr),
        }).then(() => {
          console.log('blog added');
          setHide(false);
        });
      }}
      style={{ marginLeft: '6px' }}
    >
      Mark
    </Button>
  ) : null;
};

And you can use it within your .map() and pass info as props to it.

like this:

{data.map((info) => (
  <CustomButton
    key={info.track.track_id}
    info={info}
  />)
)}

Upvotes: 0

fortunee
fortunee

Reputation: 4332

You need to manage a display of the button in a global state or handle it from the button's parent component.

Like this:

import React, { useState } from 'react';

const ParentComponent = () => {
  const [showButton, setShowButton] = useState(false);

  return (
    <>
      {showButton && (
        <Button
          className="but"
          variant="primary"
          onClick={(e) => {
            const tr = {
              id: info.track.track_id,
              trackName: info.track.track_name,
              artistName: info.track.artist_name,
            };

            fetch('http://localhost:8000/blogs', {
              method: 'POST',
              headers: { 'Content-Type': 'application/json' },
              body: JSON.stringify(tr),
            }).then(() => {
              console.log('blog added');
              setShowButton(false)
            });
          }}
          style={{ marginLeft: '6px' }}
        >
          Mark
        </Button>
      )}
    </>
  );
};

To manage state on a global level you can use the React.Context API

First, create the ButtonContext in your root app like this

const ButtonContext = React.createContext({
  showButton: true,
  setShowButton: (show) => {}
});

Wrap it around your root App and pass the value of showButton as true using the useState hook

const [showButton, setShowButton] = useState(true);

<ButtonContext.Provider value={{ showButton, setShowButton }}>
  <App />
</ButtonContext.Provider>

Then use it in your Button's ParentComponent like this

import React, { useContext } from 'react';

const ParentComponent = () => {
  const {showButton, setShowButton} = useContext(ButtonContext);

  return (
    <>
      {showButton && (
        <Button
          onClick={() => {
            // do your click stuff and
            // reset the showButton context value
            setShowButton(false)
           }
          }
        >
        </Button>)}
    </>
  )
}

Upvotes: 1

Astrit Spanca
Astrit Spanca

Reputation: 724

If you want to hide it permanently for a user then you have to register that user activity somewhere in the backend. Then send a http request so you can get data if the user can perform that activity again or not. Depending in the response you set some state and then from that state you can hide/show the button.

import React, { useEffect, useState } from 'react'

const App = () => {
  const [showButton, setShowButton] = useState(false);

  useEffect(() => {
    fetch('http://localhost:8000/can-user-perform-activity-again')
      .then((response) => response.json())
      .then((response) => {
        if(response.yes){
          setShowButton(true)
        } 
        if(response.no){
          setShowButton(false);
        }
      })
  }, []);

  return (
    <div>
      {showButton && <button>Vote</button>}
    </div>
  )
}

export default App

Upvotes: 0

Benjamin Griggs
Benjamin Griggs

Reputation: 1

use can use state to hid the button something like

{ showButton && (
   < Button className="but" variant="primary" onClick={(e)=>{
const tr={id:info.track.track_id,trackName:info.track.track_name,artistName:info.track.artist_name}

fetch('http://localhost:8000/blogs',{
 method:'POST',
 headers:{ "Content-Type": "application/json"},
 body: JSON.stringify(tr)
 } ).then(()=>{
  console.log("blog added");
    setShowButton(false);
 });
            }} style={{ marginLeft:"6px" }}>Mark</Button>
)}

Upvotes: 0

Related Questions