react-bootstrap-table2 icon indicating copy to clipboard operation
react-bootstrap-table2 copied to clipboard

I added a custom column with add and minus buttons to every row and I want onClick each + buttons, counter will be updated for that particular row only not every row?

Open dashName opened this issue 7 years ago • 30 comments

Screen Shot 2019-10-08 at 11 18 20 AM

code: const dataFormatter = (cell, row, rowIndex, formatExtraData) => {

        return (
            <div>
                <div onClick={() => addToCart(rowIndex)}>
                    <img src={plus} style={{backgroundColor: '#2a4252'}}/>
                </div>
                <div id='text-val'> {formatExtraData} </div>
                <div onClick={() => removeFromCart(rowIndex)}>
                    <img src={minus} style={{backgroundColor: '#2a4252'}}/>
                </div>
            </div>
        );
    };

and ... formatExtraData: this.state.counter, ...

const addToCart = (index) => { this.setState({counter: this.state.counter + 1}); }

...

dashName avatar Oct 08 '19 19:10 dashName

Hi, you want that when a + button is clicked the counter increase just for that specific row of the button clicked? Is that correct?

Ymbere avatar Oct 09 '19 03:10 Ymbere

Hi, you want that when a + button is clicked the counter increase just for that specific row of the button clicked? Is that correct?

Yes

dashName avatar Oct 09 '19 03:10 dashName

Could you provide the code for that component so I can help you more efficiently?

Ymbere avatar Oct 09 '19 03:10 Ymbere

Could you provide the code for that component so I can help you more efficiently? ........ constructor(props) { super(props); this.state = { counter: 0 }; } ...... const columns = [{ { dataField: '', text: 'Qty', formatter: dataFormatter, formatExtraData: this.state.counter, headerStyle: () => { return {width: '15%', textAlign: 'center', fontSize: '12px', color: '#7F7F7F'}; }, }]; .......

const dataFormatter = (cell, row, rowIndex, formatExtraData) => {

    return (
        <div>
            <div onClick={() => addToCart(rowIndex)}>
                <img src={plus} style={{backgroundColor: '#2a4252'}}/>
            </div>
            <div id='text-val'> {formatExtraData} </div>
            <div onClick={() => removeFromCart(rowIndex)}>
                <img src={minus} style={{backgroundColor: '#2a4252'}}/>
            </div>
        </div>
    );
};

..........

const addToCart = (index) => { console.log(index) this.setState({counter: this.state.counter + 1}); }

.....

dashName avatar Oct 09 '19 03:10 dashName

The problem is in the state, all the rows of the table are receiving the same state variable, so when you update one row the state is the same for all the others. In order to make each row increase the counter individually, you need to have one counter (state) for each row.

Ymbere avatar Oct 09 '19 04:10 Ymbere

The problem is in the state, all the rows of the table are receiving the same state variable, so when you update one row the state is the same for all the others. In order to make each row increase the counter individually, you need to have one counter (state) for each row.

can we do something with rowIndex?If not how we are gonna have counters for each row?can you please suggest the best way to achieve this?

dashName avatar Oct 09 '19 04:10 dashName

The items to be displayed in the table are received as props in the component?

Ymbere avatar Oct 09 '19 04:10 Ymbere

The items to be displayed in the table are received as props in the component?

yes

dashName avatar Oct 09 '19 04:10 dashName

The items to be displayed in the table are received as props in the component?

yes

My approach is the following after you receive your table data as props you can iterate through then, this way you add a default counter for each row.

  state = {
    tableCounters: []
  };
  componentDidMount() {
    const tableCounters = [];
    const tableData = this.props.myTableData;

    tableData.forEach(() => {
      tableCounters.push({ counter: 0 });
    });

    this.setState({ tableCounters });
  }

After that, you can implement the method getCounter and pass it to your formatExtraData

  getCounter = rowIndex => {
    if (this.state.tableCounters[rowIndex] !== undefined) {
      return this.state.tableCounters[rowIndex].counter;
    }
  };

And your dataFormatter will look like this

const dataFormatter = (cell, row, rowIndex, formatExtraData) => {
  return (
    <div>
      <div onClick={() => addToCart(rowIndex)}>
        <img src={plus} style={{ backgroundColor: "#2a4252" }} />
      </div>
      <div id="text-val"> {formatExtraData(rowIndex)} </div>
      <div onClick={() => removeFromCart(rowIndex)}>
        <img src={minus} style={{ backgroundColor: "#2a4252" }} />
      </div>
    </div>
  );
};

With that done you need to update your addToCart in order to update the counter for the specific row index

Ymbere avatar Oct 09 '19 05:10 Ymbere

The items to be displayed in the table are received as props in the component?

yes

My approach is the following after you receive your table data as props you can iterate through then, this way you add a default counter for each row.

  state = {
    tableCounters: []
  };
  componentDidMount() {
    const tableCounters = [];
    const tableData = this.props.myTableData;

    tableData.forEach(() => {
      tableCounters.push({ counter: 0 });
    });

    this.setState({ tableCounters });
  }

After that, you can implement the method getCounter and pass it to your formatExtraData

  getCounter = rowIndex => {
    if (this.state.tableCounters[rowIndex] !== undefined) {
      return this.state.tableCounters[rowIndex].counter;
    }
  };

And your dataFormatter will look like this

const dataFormatter = (cell, row, rowIndex, formatExtraData) => {
  return (
    <div>
      <div onClick={() => addToCart(rowIndex)}>
        <img src={plus} style={{ backgroundColor: "#2a4252" }} />
      </div>
      <div id="text-val"> {formatExtraData(rowIndex)} </div>
      <div onClick={() => removeFromCart(rowIndex)}>
        <img src={minus} style={{ backgroundColor: "#2a4252" }} />
      </div>
    </div>
  );
};

With that done you need to update your addToCart in order to update the counter for the specific row index

Hey I tried like below but does not seem to work. .... this.state = { counter: 0, tableCounters: [] }; ....

componentDidUpdate(prevProps, prevState) {
    const tableCounters = [];
    const tableData = this.props.data;
    tableData.forEach(() => {
        tableCounters.push({counter: 0});
    });
    if (this.props.data !== prevProps.data) {
        this.setState({tableCounters: tableCounters});
    }
}

getCounter = rowIndex => {
    if (this.state.tableCounters[rowIndex] !== undefined) {
        return this.state.tableCounters[rowIndex].counter;
    }
};

....

const dataFormatter = (cell, row, rowIndex, formatExtraData) => { return (

<div onClick={() => addToCart(rowIndex)}> <img src={plus} style={{backgroundColor: '#2a4252'}}/>
<div style={{backgroundColor: '#fff', padding: '2px 5px', outline: 'none'}} id='text-val'> {formatExtraData(rowIndex)}
<div onClick={() => removeFromCart()}> <img src={minus} style={{backgroundColor: '#2a4252'}}/>
); }; ........ const addToCart = (index) => { this.setState({counter: this.state.tableCounters[index].counter + 1}); }

dashName avatar Oct 09 '19 15:10 dashName

Hi @dashName , your state should be like this

  state = {
    tableCounters: []
  };

And your addToCart method should loop through the array of state counters and then update the state counter for the specific row, the way that you implemented it will do not work because it is setting the state on the "global" counter.

I think this will do the trick

  addToCard = rowIndex => {
    this.setState(prevState => ({
      tableCounters: prevState.tableCounters.map((item, index) => {
        if (index === rowIndex) {
          return { counter: item.counter + 1 };
        }
        return item;
      })
    }));
  }

And the componentDidUpdate should be componentDidMount

Ymbere avatar Oct 10 '19 03:10 Ymbere

Hi @dashName , your state should be like this

  state = {
    tableCounters: []
  };

And your addToCart method should loop through the array of state counters and then update the state counter for the specific row, the way that you implemented it will do not work because it is setting the state on the "global" counter.

I think this will do the trick

  addToCard = rowIndex => {
    this.setState(prevState => ({
      tableCounters: prevState.tableCounters.map((item, index) => {
        if (index === rowIndex) {
          return { counter: item.counter + 1 };
        }
        return item;
      })
    }));
  }

And the componentDidUpdate should be componentDidMount

ComponentDidMount was returning props value as undefined so i used componentDidUpdate..Thanks a lot for the solution..it works..really appreciate

dashName avatar Oct 10 '19 03:10 dashName

Hi @dashName , your state should be like this

  state = {
    tableCounters: []
  };

And your addToCart method should loop through the array of state counters and then update the state counter for the specific row, the way that you implemented it will do not work because it is setting the state on the "global" counter. I think this will do the trick

  addToCard = rowIndex => {
    this.setState(prevState => ({
      tableCounters: prevState.tableCounters.map((item, index) => {
        if (index === rowIndex) {
          return { counter: item.counter + 1 };
        }
        return item;
      })
    }));
  }

And the componentDidUpdate should be componentDidMount

ComponentDidMount was returning props value as undefined so i used componentDidUpdate..Thanks a lot for the solution..it works..really appreciate

No problem

Ymbere avatar Oct 10 '19 03:10 Ymbere

Hi @dashName , your state should be like this

  state = {
    tableCounters: []
  };

And your addToCart method should loop through the array of state counters and then update the state counter for the specific row, the way that you implemented it will do not work because it is setting the state on the "global" counter. I think this will do the trick

  addToCard = rowIndex => {
    this.setState(prevState => ({
      tableCounters: prevState.tableCounters.map((item, index) => {
        if (index === rowIndex) {
          return { counter: item.counter + 1 };
        }
        return item;
      })
    }));
  }

And the componentDidUpdate should be componentDidMount

ComponentDidMount was returning props value as undefined so i used componentDidUpdate..Thanks a lot for the solution..it works..really appreciate

No problem

On above context: ...

Currently it takes {formatExtraData(rowIndex)} data as the value but I want to support userInput as well , i.e make the div editable so that it can accepts the userInput numbers as well is it possible to support both features?

To be more specific override the formatExtraData(rowIndex) with user input, whenever there is a userInput

{formatExtraData(rowIndex)}

I tried with cell property but , celleditfactory is for whole cell right but here I dont want to do for whole cell but only the part of it

dashName avatar Oct 16 '19 00:10 dashName

Hi, you can change the div that contains the number to a input so you can attach onChange method to it and support user input.

  const dataFormatter = (cell, row, rowIndex, formatExtraData) => {
    return (
      <div>
        <div onClick={() => addToCart(rowIndex)}>
          <img src={plus} style={{ backgroundColor: "#2a4252" }} />
        </div>
        <input
          id="input-quantity"
          value={formatExtraData(rowIndex)}
          onChange={// Custom on change goes here}
        />
        <div onClick={() => removeFromCart(rowIndex)}>
          <img src={minus} style={{ backgroundColor: "#2a4252" }} />
        </div>
      </div>
    );
  };

Ymbere avatar Oct 18 '19 16:10 Ymbere

@dashName, you can send your custom onChange method, so I can see if is there any problem?

Ymbere avatar Oct 18 '19 17:10 Ymbere

@dashName, you can send your custom onChange method, so I can see if is there any problem?

 const handleChange = (e) => {
        console.log(e.currentTarget.value,row)
        this.setState(prevState => ({
            tableCounters: prevState.tableCounters.map((item, index) => {
                    return { counter: e.currentTarget.value };
            })
        }));

    };

it is updating the value,but not sure how I am gonna pass the row value from dataFormatter to access addToCart

<input style={{backgroundColor: '#fff', padding: '2px 5px', outline: 'none'}} id='text-val' value={formatExtraData(rowIndex)} onChange={handleChange}/>

dashName avatar Oct 18 '19 17:10 dashName

Your onChange method is not actually changing the counter for a specific row, you need to pass along with the event the row index that you want to change the counter.

Like this

onChange={e => onChange(rowIndex, e)}

Your onChange method will look like this

  handleChange = (rowIndex, e) => {
    this.setState(prevState => ({
      tableCounters: prevState.tableCounters.map((item, index) => {
        if (index === rowIndex) {
          return { counter: e.currentTarget.value };
        }
        return item;
      })
    }));
  };

Ymbere avatar Oct 18 '19 17:10 Ymbere

Your onChange method is not actually changing the counter for a specific row, you need to pass along with the event the row index that you want to change the counter.

Like this

onChange={e => onChange(rowIndex, e)}

Your onChange method will look like this

  handleChange = (rowIndex, e) => {
    this.setState(prevState => ({
      tableCounters: prevState.tableCounters.map((item, index) => {
        if (index === rowIndex) {
          return { counter: e.currentTarget.value };
        }
        return item;
      })
    }));
  };

yes you are right.Thanks

dashName avatar Oct 18 '19 21:10 dashName

Hi @dashName, it worked properly?

Ymbere avatar Oct 19 '19 02:10 Ymbere