S. Schenk S. Schenk - 3 months ago 10
React JSX Question

How do I set an attribute on a prop after an onClick event?

I have a button with an onClick event that sends a value to my state and should remove it from the state on a second click:

<button
type="button"
value={posts.index}
onClick={this.props.data ? this.props.remove : this.props.add}
key={cont._id}
data={-1}
>


My problem is that I dunno how to set the data attribute to 1 after the first click, so the second click would fire the remove function. How do I achieve that?

action creator

export function add(e) {
return{
type: ADD,
payload: e.target.value
}

}

Answer

I'm assuming the data attribute in prop contains the value you want the data attribute to contain.

First, ensure that in the parent component, data is defined as a state property, so that it can be manipulated to affect both the parent and the button.

Next, define the add() and remove() functions to look like:

add() {
  this.setState({data: this.state.data + 1});
}

remove() {
  this.setState({data: this.state.data - 1});
}

And of course, the constructor bind to this scope (still on the parent)

constructor(props, context) {
  this.add = this.add.bind(this)
  this.remove = this.remove.bind(this)
}

With these done, you can then define your button as:

<button 
  type="button" 
  value={posts.index} 
  onClick={this.props.data ? this.props.remove : this.props.add}
  key={cont._id}
  data={this.props.data} > 

React strongest belief is that changes in the DOM be triggered by data. With this setup, anytime you make any change to the parent data attribute by calling the add() or remove() callback, the button is re-rendered to reflect the new value of data.