1

My question is, how can I disable a particular button in a Button array depends on a click? Below there is a SearchField component which consists of multiple buttons in it, I want to disable just the button clicked, but all the buttons turn to disabled, how can I solve this?

 state = {
        redirect: false,
        loading: false,
        alreadyAddedFav: false,
        disabled: false
    }




onClickedHandler = (recipe_id, token) => {
        if (!this.props.isAuthenticated) {
            this.setState({ redirect: true })
        }
        else {
            const favData = {
                recipe_id: recipe_id,
                userId: this.props.userId
            }
            if (this.props.favRecipes.length > 0) {

                if (!this.props.favRecipes.some(item => item.recipe_id === recipe_id)) {

                    console.log("added in the loop!")
                    this.props.onFav(favData, token);
                    this.setState({ disabled: true });
                } else {
                    this.setState({ alreadyAddedFav: true })
                    console.log("it is already in the fav list!")
                    console.log(recipe_id)
                }

            } else {
                this.props.onFav(favData, token);
                this.setState({ disabled: true });
            }
        }
    }





     render() {
       return (
                 <SearchResult
                            disabled={this.state.disabled}
                            key={ig.recipe_id}
                            title={ig.title}
                            imgSrc={ig.image_url}
                            clicked={() => this.onClickedHandler(ig.recipe_id, this.props.token)}
                        >
                        </SearchResult>)}
3
  • You should keep a separate state property in your parent for the buttons. You can use index and can specify which button will be disabled according to this index. In your situation, all the buttons get the same disabled property. Commented Oct 4, 2018 at 22:11
  • yeah actually I figured out I can use index in the map, but couldn't achieve, if you can show me an example via jsfiddler or JSbin it would be cool Commented Oct 4, 2018 at 22:16
  • This probably depends on how you map your buttons. By the way, are those recipe_ids can be associated with the buttons somehow? If yes, then maybe you can use the ids to specify the disabled buttons. Commented Oct 4, 2018 at 22:18

1 Answer 1

2

Here is a simple example, maybe you can enhance this according to your situation.

class App extends React.Component {
  state = {
    disableds: [],
  };

  handleClick = i =>
    this.setState( currentState => ( {
      disableds: [ ...currentState.disableds, i ],
    } ) );

  render() {
    return (
      <div className="App">
        <Buttons onClick={this.handleClick} disableds={this.state.disableds} />
      </div>
    );
  }
}

const Buttons = ( props ) => {
  const buttons = [ { text: "foo" }, { text: "bar" }, { text: "baz" } ];
  return (
    <div>
      {buttons.map( ( button, i ) => (
        <button
          key={button.text}
          disabled={props.disableds.includes( i )}
          onClick={() => props.onClick( i )}
        >
          {button.text}
        </button>
      ) )}
    </div>
  );
};

ReactDOM.render( <App />, document.getElementById( "root" ) );
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

What I don't like here is the way I added the onClick handler to the button element. In this way, this arrow function will be recreated in every render. Not so big deal but I prefer using function references. To avoid this we can extract each button element into its component and use a separate handler again.

Sign up to request clarification or add additional context in comments.

2 Comments

Yes, I did it! thank you very much, it is an important concept for me to be used for upcoming situations
You are welcome. Yes, it is a nice technique for that kind of situations. I would rather prefer using some unique values to keep the disabled value if possible (like an id) since indexes would be inconsistent.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.