Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access props outside of a class component React

Tags:

I'm having trouble understanding how to access props defined outside of a class component in React.

In the following code all props are defined except for this.props.checkboxArray which currently returns "cannot read property 'props' of undefined."

I know 'this' is not defined outside of the class component so I have tried binding 'this' to checkboxArray but still the same error that 'props' is undefined.

    let checkboxObject = this.props.checkboxArray.reduce(
      (name, boolean) => ({
        ...name,
        [boolean]: false
      }),
      {}
    );

    class CheckboxList extends Component {
      constructor(props) {
        super(props);
        this.state = { checkbox: checkboxObject };

        this.checkboxArray = this.checkboxArray.bind(this);
      }

      handleCheckboxChange = name => {
        let checkbox = this.state.checkbox;
        for (var key in checkbox) {
          if (key === name) {
            checkbox[key] = !checkbox[key];
          }
        }
        this.setState({ checkbox });
      };

      render() {
        return (
          <div className="row" id="CheckboxList">
            {this.props.checkBoxArray.map(checkbox => (
              <Checkbox
                label={checkbox}
                isSelected={checkboxObject[checkbox]}
                onCheckboxChange={this.props.onCheckboxTick}
                key={checkbox}
              />
            ))}
          </div>
    );
  }
}

export default CheckboxList;
like image 449
ctb116 Avatar asked Feb 22 '19 02:02

ctb116


1 Answers

You should create a function to call checkboxObject like:

const createCheckboxes =  checkboxArray => checkboxArray.reduce(
      (name, boolean) => ({
        ...name,
        [boolean]: false
      }),
      {}
    );

and call this funtion on your class component: createCheckboxes(this.props.checkboxArray)

Btw, this is not the best practice. Your checkbox should be editted on it's parent component using Selector

like image 186
Vu Luu Avatar answered Nov 15 '22 04:11

Vu Luu