5

Button Component (Child)

export default class Button extends React.Component {
  render() {
    var handleToUpdate = this.props.handleToUpdate;
    return (
      <button onClick={() => handleToUpdate(this.id)}>
        {this.props.title}
      </button>
    );
  }
}

Index(Parent)
in return

<Button title={title1} handleToUpdate={handleToUpdate.bind(this)} />
<Button title={title2} handleToUpdate={handleToUpdate1.bind(this)} />
<Button title={title3} />
<Button title={title4} />

in render

const title1 = "test1"
const title2 = "test2"
const title3 = "test3"
const title4 = "test4"
var handleToUpdate = this.handleToUpdate;
var handleToUpdate1 = this.handleToUpdate1;

function

  handleToUpdate() {
  this.setState({})
  }

  handleToUpdate1() {
  this.setState({})
  }

var handleToUpdate = this.handleToUpdate.bind(this);
var handleToUpdate1 = this.handleToUpdate1.bind(this);

There is no issue in my code but my way of approaching to the function is not good practice I believe.

What I am doing here is I made button component(Child) and calling it four times in the parent(index). I created onClick props to call function and then set state.

Is there any alternative method that I can create one function with 4 setState and call the state according to the button id which is clicked.

To Make it more clear.

Button 1 clicked => call singlefunction => setstate1

Button 2 clicked => cal singlefunction => setstate 2 ...

7
  • 1
    You could pass the button click event to the handToUpdate function and then do switch statement to determine which button was clicked, and then you can set the corresponding state ?
    – ProEvilz
    Commented Oct 11, 2018 at 1:02
  • @AshleyBrown is it possible can you provide me a piece of code or same example. please Commented Oct 11, 2018 at 1:03
  • Done, check out my answer.
    – ProEvilz
    Commented Oct 11, 2018 at 1:07
  • Where do you keep the id?
    – devserkan
    Commented Oct 11, 2018 at 1:14
  • store it on the individual buttons? i assumed you had that already set up since you pass (this.id)
    – ProEvilz
    Commented Oct 11, 2018 at 1:17

3 Answers 3

3

If you are passing the id to the Button component, here is an alternative approach.

const buttons = [
  { id: 1, title: "test1" },
  { id: 2, title: "test2" },
  { id: 3, title: "test3" },
];

class App extends React.Component {
  state = {
    clicked: "",
  };

  onUpdate = ( id ) => {
    this.setState( { clicked: id } );
  };

  render() {
    console.log( this.state );
    return (
      <div>
        {buttons.map( button => (
          <Button
            key={button.id}
            button={button}
            onUpdate={this.onUpdate}
          />
        ) )}
      </div>
    );
  }
}

const Button = ( props ) => {
  const { button, onUpdate } = props;
  const handleUpdate = () => onUpdate( button.id );
  return <button onClick={handleUpdate}>{button.title}</button>;
};

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>

8
  • Why would you make an object with an id? Each array member would already have an index. Commented Oct 11, 2018 at 1:27
  • 1
    Indexes are not good every time. I know probably order won't change here, so using an index would be fine but I prefer using id's if I create my own lists.
    – devserkan
    Commented Oct 11, 2018 at 1:28
  • that's fair, but at that point why not just use the title directly? Commented Oct 11, 2018 at 1:29
  • 1
    If you are asking for the key since the code is just a fake one I can' be sure the titles are unique or not. This is barely an example :)
    – devserkan
    Commented Oct 11, 2018 at 1:31
  • Ah, also if I do some operations about this item, dealing with ids is easier than dealing with indexes. One filter is enough for that. No hassle for finding indexes.
    – devserkan
    Commented Oct 11, 2018 at 1:33
2

I would do something like this:

render(){
    const titles = ['title1', 'title2', 'title3', 'title4'];

  return(
    {
     titles.map((title, i)=>(
     <Button title={title} key={i} 
             handleToUpdate={()=>this.handleToUpdate(i)} />
               ))
    }
} 

in your handleToUpdate function/method, you should then use the parameter i to determine what is done. You could also use a parameter like (e)=>this.handleToUpdate(e) and then name the button with the title and access the name via e.target as follows:

handleToUpdate(e){
   const {name} = e.target;
   this.setState({[name]: true});
}

You can replace true in set state to whatever you want, however using a boolean is best if you are doing an action with a single potential result, i.e. always setting state in the same way as you presented in your question.

To pass the function with an id directly in the case of different locations for your buttons do this:

<Button title={title1} handleToUpdate={()=>this.handleToUpdate(1)} />

where 1 is an index with any number to plugin, or any key to use in a switch statement.

In your Button component change the onClick to:

<button onClick={this.props.handleToUpdate}> {this.props.title} </button>

You are basically binding the parameter to the function directly as in the map function I have above.

With this solution, you can just do a switch statement like in Ashley Brown's answer.

0
1

You can use a switch to determine which button was clicked based on the id you passed in... Alternatively you could have passed in the event if you hadn't have passed in the id already. Just be sure to set up the props if you haven't already...

export default class Button extends React.Component {
  render() {
    var handleToUpdate = this.props.handleToUpdate;
    return (
      <button onClick={() => handleToUpdate(this.id)}> // <- this id you passed in
        {this.props.title}
      </button>
    );
  }
}


<Button id={1} title={title1} handleToUpdate={handleToUpdate.bind(this)} />
<Button id={2} title={title2} handleToUpdate={handleToUpdate.bind(this)} />

handleToUpdate(id) { // <-- id passed in
  switch(id) {
   case 1: // if id === 1
    //setState({})
   break;

   case 2: // if id === 2
    //setState({})
   break;
   // etc
 } 
}
8
  • 1
    If the title prop is is unique you could just pass that to the onClick function but otherwise follow this pattern. Commented Oct 11, 2018 at 1:14
  • @Ashley Brown It is not able to take ID in a switch statement. Showing undefined in the console. Commented Oct 11, 2018 at 1:27
  • It's probably something to do with the this.id I can't tell where it's coming from at a glance. Commented Oct 11, 2018 at 1:32
  • @DavidKamer I believe so but I like the approach using a switch statement. Is there any way I can get ID value in switch statement. Commented Oct 11, 2018 at 1:38
  • @contactdummy look at my answer and pass your id to the button like I am showing. Ignore the last half of the question if you don't care about it. Commented Oct 11, 2018 at 1:39

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.