0

Want to get all selected check box values in one array. But onChange function is giving error as undefined. I have posted the full component here.

I need checkedValues =[]`

let my imgUrls: imgUrls = [ "https://dummyimage.com/100x100/bc6666/FFFFFF/&text=img-3","https://dummyimage.com/100x100/bc6666/FFFFFF/&text=img-4","https://dummyimage.com/100x100/bc6666/FFFFFF/&text=img-5","https://dummyimage.com/100x100/bc6666/FFFFFF/&text=img-6"]

var checkedValue =["https://dummyimage.com/100x100/bc6666/FFFFFF/&text=img-4","https://dummyimage.com/100x100/bc6666/FFFFFF/&text=img-5"]`

var imgUrls = [ "https://dummyimage.com/100x100/bc6666/FFFFFF/&text=img-3","https://dummyimage.com/100x100/bc6666/FFFFFF/&text=img-4","https://dummyimage.com/100x100/bc6666/FFFFFF/&text=img-5","https://dummyimage.com/100x100/bc6666/FFFFFF/&text=img-6"]

import React from 'react';


export default class Mycomp extends React.Component {

constructor(props) {
    super(props);
    this.url = "https://dummyimage.com/100x100";
    this.count = 0;
    this.tempImgUrls = [];

    this.state = {
        bgColor: '#bc6666',
        textColor: '#FFFFFF',
        imgCountsStart: 0,
        imgCountsEnd: 0,
        imgUrls: [],
        showMore: false,
        slectedItems: 0,
        checkedValues: []
    }
}

bgColorhandleChange = (event) => {
    this.setState({
        bgColor: event.target.value
    });
}
textColorhandleChange = (event) => {
    this.setState({
        textColor: event.target.value
    });
}
imgCountsStarthandleChange = (event) => {
    this.setState({
        imgCountsStart: event.target.value
    })
}
imgCountsEndhandleChange = (event) => {
    this.setState({
        imgCountsEnd: event.target.value
    })
}
myhandelchange = (event) => {
    this.setState({
        ischecked: true
    })
}
handleSubmit = () => {
    this.tempImgUrls = [];
    this.setState({
        imgUrls: this.tempImgUrls
    })

    this.count = 0;
    for (let i = 0; i <= this.state.imgCountsEnd - this.state.imgCountsStart; i++) {
        let imgtextcount = parseFloat(this.count) + parseFloat(this.state.imgCountsStart)
        this.url = this.url + "/" + this.state.bgColor.slice(1) + '/' + this.state.textColor.slice(1) + '/' +
            '&text=img-' + imgtextcount
        this.count += 1;
        this.tempImgUrls.push(this.url);
        this.url = 'https://dummyimage.com/100x100';
    }
    this.setState({
        imgCountsEnd: 0
    });
    this.setState({
        imgCountsStart: 0
    });

    console.log(this.tempImgUrls)

    if (this.state.imgCountsEnd - this.state.imgCountsStart < 10) {
        this.setState({
            imgUrls: this.tempImgUrls
        })
    } else if (this.state.imgCountsEnd - this.state.imgCountsStart > 10) {
        this.setState({
            showMore: true
        })
        let tempvari = this.tempImgUrls.slice(0, 10)

        this.setState({
            imgUrls: tempvari
        })
        this.tempImgUrls = this.tempImgUrls.slice(10);
    }
} 

loadMoreImage = () => {
    this.setState({
        imgUrls: []
    })
    let tempvari2 = this.tempImgUrls.slice(0, 10);
    this.setState({
        imgUrls: tempvari2
    })
    this.tempImgUrls = this.tempImgUrls.slice(10);
    if (this.tempImgUrls.length === 0) {
        this.setState({
            showMore: false
        })
    }
}
clearAll = () => {
    this.setState({
        bgColor: '#bc6666',
        textColor: '#FFFFFF',
        imgCountsStart: 0,
        imgCountsEnd: 0,
        imgUrls: [],
        showMore: false,
    })
}

render() {
    return (
        <React.Fragment>
            <form>
                <div className="form-row">
                    <div className="form-group col-md-3">
                        <label htmlFor="bgColorImg">Background Color of Image</label>
                        <input type="color" className="form-control" id="bgColorImg" placeholder="Color"
                            value={this.state.bgColor} onChange={this.bgColorhandleChange} />
                    </div>
                    <div className="form-group col-md-3">
                        <label htmlFor="textColor">Color Of The Text</label>
                        <input type="color" className="form-control" id="textColor" placeholder="Input Color"
                            value={this.state.textColor} onChange={this.textColorhandleChange} />
                    </div>
                    <div className="form-group col-md-3">
                        <label htmlFor="imgCountsStart">No. Of Images starting at</label>
                        <input type="number" min={0} className="form-control" id="imgCountsStart" placeholder="No of Image start"
                            value={this.state.imgCountsStart} onChange={this.imgCountsStarthandleChange} />
                    </div>
                    <div className="form-group col-md-3">
                        <label htmlFor="imgCountsEnd">No. Of Images ends at</label>
                        <input type="number" min={0} className="form-control" id="imgCountsEnd" placeholder="No of Imageend "
                            value={this.state.imgCountsEnd} onChange={this.imgCountsEndhandleChange} />
                    </div>
                </div>
                <button type="button" className="btn btn-secondary" onClick={this.handleSubmit}
                    onChange={this.disableBtn} disabled={this.state.imgCountsEnd === 0 && this.state.imgCountsStart === 0}>Show Photos</button>
                <button type="button" className="btn btn-secondary" onClick={this.clearAll}
                    disabled={this.state.imgUrls.length === 0} >Clear All</button>
            </form>

            {/* <div>Showing from {this.state.imgCountsStart} to {this.state.imgCountsEnd}</div> */}
            <div>
                <ul>
                    {this.state.imgUrls.map(function (name, index) {
                        return <li key={index}>
                            <input type="checkbox" id={name} name={name}/>
                            <label htmlFor={name}>
                                <img alt={name} src={name} value={name} />
                            </label>
                        </li>
                    })}
                </ul>
            </div>
                    
            {this.state.showMore ? <button className='btn btn-warning' onClick={this.loadMoreImage}>Load More</button> : ''}

            <button disabled={this.state.slectedItems == 0} type="button" className="btn btn-md btn-secondary"
                data-toggle="modal" data-target="#myModal">
                Your Selection
            </button>
            <div className="modal" id="myModal">
                <div className="modal-dialog">
                    <div className="modal-content">
                        <div className="modal-header">
                            <h4 className="modal-title">Total Number of Selection</h4>
                            <button type="button" className="close" data-dismiss="modal">&times;</button>
                        </div>
                        <div className="modal-body">
                            Selected Items :
                        </div>
                        <div className="modal-footer">
                            <button type="button" className="btn btn-danger" data-dismiss="modal">Close</button>
                        </div>
                    </div>
                </div>
            </div>
        </React.Fragment>
    )
}
}

1
  • see my solution below and let me know if it works for you :) Commented Jul 14, 2019 at 20:25

2 Answers 2

1

It's because you're not using an arrow-function for your .map() callback function, so the this keyword is not bound to that execution context. Use an arrow-function instead:

See sandbox: https://codesandbox.io/s/focused-glade-yfl8j

import React from "react";
import ReactDOM from "react-dom";

import "./styles.css";

class App extends React.Component {
  state = {
    checkedValues: [],
    imgUrls: [
      "https://dummyimage.com/100x100/bc6666/FFFFFF/&text=img-3",
      "https://dummyimage.com/100x100/bc6666/FFFFFF/&text=img-4",
      "https://dummyimage.com/100x100/bc6666/FFFFFF/&text=img-5",
      "https://dummyimage.com/100x100/bc6666/FFFFFF/&text=img-6"
    ]
  };

  funValue = e => {
    const { checkedValues } = this.state;
    let updatedCheckedValues = [];
    if (checkedValues.includes(e.target.value)) {
      updatedCheckedValues = checkedValues.filter(
        value => value !== e.target.value
      );
    } else {
      updatedCheckedValues = [...checkedValues, e.target.value];
    }

    this.setState(
      {
        checkedValues: updatedCheckedValues
      },
      () => console.log(this.state)
    );
  };

  render() {
    return (
      <div>
        <ul>
          {this.state.imgUrls.map((name, index) => {
            return (
              <li key={index}>
                <input
                  onChange={this.funValue}
                  type="checkbox"
                  id={name}
                  name={name}
                  value={name}
                />
                <label htmlFor={name}>
                  <img alt={name} src={name} value={name} />
                </label>
              </li>
            );
          })}
        </ul>
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for your help. But it was giving the same error. I have posted the full component below.
@SoubhagyaJena hmm it looks like you never updated the .map() function in your code above?
@SoubhagyaJena here's the updated sandbox as well: codesandbox.io/s/focused-glade-yfl8j
0

import React from 'react';

export default class Mycomp extends React.Component {

constructor(props) {
    super(props);
    this.url = "https://dummyimage.com/100x100";
    this.count = 0;
    this.tempImgUrls = [];

    this.state = {
        bgColor: '#bc6666',
        textColor: '#FFFFFF',
        imgCountsStart: 0,
        imgCountsEnd: 0,
        imgUrls: [],
        showMore: false,
        slectedItems: 0,
        checkedValues: []
    }
}

bgColorhandleChange = (event) => {
    this.setState({
        bgColor: event.target.value
    });
}
textColorhandleChange = (event) => {
    this.setState({
        textColor: event.target.value
    });
}
imgCountsStarthandleChange = (event) => {
    this.setState({
        imgCountsStart: event.target.value
    })
}
imgCountsEndhandleChange = (event) => {
    this.setState({
        imgCountsEnd: event.target.value
    })
}
myhandelchange = (event) => {
    this.setState({
        ischecked: true
    })
}
handleSubmit = () => {
    this.tempImgUrls = [];
    this.setState({
        imgUrls: this.tempImgUrls
    })

    this.count = 0;
    for (let i = 0; i <= this.state.imgCountsEnd - this.state.imgCountsStart; i++) {
        let imgtextcount = parseFloat(this.count) + parseFloat(this.state.imgCountsStart)
        this.url = this.url + "/" + this.state.bgColor.slice(1) + '/' + this.state.textColor.slice(1) + '/' +
            '&text=img-' + imgtextcount
        this.count += 1;
        this.tempImgUrls.push(this.url);
        this.url = 'https://dummyimage.com/100x100';
    }
    this.setState({
        imgCountsEnd: 0
    });
    this.setState({
        imgCountsStart: 0
    });

    console.log(this.tempImgUrls)

    if (this.state.imgCountsEnd - this.state.imgCountsStart < 10) {
        this.setState({
            imgUrls: this.tempImgUrls
        })
    } else if (this.state.imgCountsEnd - this.state.imgCountsStart > 10) {
        this.setState({
            showMore: true
        })
        let tempvari = this.tempImgUrls.slice(0, 10)

        this.setState({
            imgUrls: tempvari
        })
        this.tempImgUrls = this.tempImgUrls.slice(10);
    }
}
funValue = e => {
    const { checkedValues } = this.state.checkedValues;
    let updatedCheckedValues = [];
    if (checkedValues.includes(e.target.value)) {
      updatedCheckedValues = checkedValues.filter(
        value => value !== e.target.value
      );
    } else {
      updatedCheckedValues = [...checkedValues, e.target.value];
    }

    this.setState(
      {
        checkedValues: updatedCheckedValues
      },
      () => console.log(this.state)
    );
  };

loadMoreImage = () => {
    this.setState({
        imgUrls: []
    })
    let tempvari2 = this.tempImgUrls.slice(0, 10);
    this.setState({
        imgUrls: tempvari2
    })
    this.tempImgUrls = this.tempImgUrls.slice(10);
    if (this.tempImgUrls.length === 0) {
        this.setState({
            showMore: false
        })
    }
}
clearAll = () => {
    this.setState({
        bgColor: '#bc6666',
        textColor: '#FFFFFF',
        imgCountsStart: 0,
        imgCountsEnd: 0,
        imgUrls: [],
        showMore: false,
    })
}

render() {
    return (
        <React.Fragment>
            <form>
                <div className="form-row">
                    <div className="form-group col-md-3">
                        <label htmlFor="bgColorImg">Background Color of Image</label>
                        <input type="color" className="form-control" id="bgColorImg" placeholder="Color"
                            value={this.state.bgColor} onChange={this.bgColorhandleChange} />
                    </div>
                    <div className="form-group col-md-3">
                        <label htmlFor="textColor">Color Of The Text</label>
                        <input type="color" className="form-control" id="textColor" placeholder="Input Color"
                            value={this.state.textColor} onChange={this.textColorhandleChange} />
                    </div>
                    <div className="form-group col-md-3">
                        <label htmlFor="imgCountsStart">No. Of Images starting at</label>
                        <input type="number" min={0} className="form-control" id="imgCountsStart" placeholder="No of Image start"
                            value={this.state.imgCountsStart} onChange={this.imgCountsStarthandleChange} />
                    </div>
                    <div className="form-group col-md-3">
                        <label htmlFor="imgCountsEnd">No. Of Images ends at</label>
                        <input type="number" min={0} className="form-control" id="imgCountsEnd" placeholder="No of Imageend "
                            value={this.state.imgCountsEnd} onChange={this.imgCountsEndhandleChange} />
                    </div>
                </div>
                <button type="button" className="btn btn-secondary" onClick={this.handleSubmit}
                    onChange={this.disableBtn} disabled={this.state.imgCountsEnd === 0 && this.state.imgCountsStart === 0}>Show Photos</button>
                <button type="button" className="btn btn-secondary" onClick={this.clearAll}
                    disabled={this.state.imgUrls.length === 0} >Clear All</button>
            </form>

            {/* <div>Showing from {this.state.imgCountsStart} to {this.state.imgCountsEnd}</div> */}
            <div>
                <ul>
                    {this.state.imgUrls.map(function (name, index) {
                        return <li key={index}>
                            <input type="checkbox" id={name} name={name} onChange={this.funValue}/>
                            <label htmlFor={name}>
                                <img alt={name} src={name} value={name} />
                            </label>
                        </li>
                    })}
                </ul>
            </div>

            {this.state.showMore ? <button className='btn btn-warning' onClick={this.loadMoreImage}>Load More</button> : ''}

            <button disabled={this.state.slectedItems == 0} type="button" className="btn btn-md btn-secondary"
                data-toggle="modal" data-target="#myModal">
                Your Selection
            </button>
            <div className="modal" id="myModal">
                <div className="modal-dialog">
                    <div className="modal-content">
                        <div className="modal-header">
                            <h4 className="modal-title">Total Number of Selection</h4>
                            <button type="button" className="close" data-dismiss="modal">&times;</button>
                        </div>
                        <div className="modal-body">
                            Selected Items :
                        </div>
                        <div className="modal-footer">
                            <button type="button" className="btn btn-danger" data-dismiss="modal">Close</button>
                        </div>
                    </div>
                </div>
            </div>
        </React.Fragment>
    )
}

}

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.