Abhinav Satpathi
Abhinav Satpathi

Reputation: 1

how to update a children component when the value of state change

I know this question is common in react but this is a little different.

I am generating a barcode for my products dynamically by selecting my products from the dropdown like this:

Example Image

First the value of state is example but it changes with the on select event from dropdown.

When my page renders, first it generates the barcode for example but my value changed by selecting dropdown it dint generate the barcode for my next value there is code and library.

class QRCodePage extends Component {
  constructor() {
    super();
    this.state = {
      productid: "exaple"
    };
  }
  setQRCode(event) {
    this.setState = {
      productid: event.target.value
    };
  }
  render() {
    return (
      <div>
        <FormControl
          componentClass="select"
          placeholder="Select Product"
          onChange={this.setQRCode.bind(this)}
          required
        >
          <option value="">select</option>
          {this.props.products.map((product, i) =>
            <option key={i} value={product._id}>
              {product.productName}
            </option>
          )}
        </FormControl>
        <Barcode value={this.state.productid} />
      </div>
    );
  }
}

Upvotes: 0

Views: 137

Answers (1)

Nocebo
Nocebo

Reputation: 2017

Try to do this instead. It doesn't solve this issue but it's cleaner and better code. Also try to do this and tell me what the console says.

class QRCodePage extends Component {
  state = {
    productid: "exaple"
  };
  setQRCode = event => {
    //Note the arrow function, which binds the function to the component.
    //This way you can use "this" in the correct scope
    this.setState(
      {
        productid: event.target.value
      },
      () => {
        console.log(this.state.productid);
      }
    );
  };

  render() {
    return (
      <div>
        <FormControl
          componentClass="select"
          placeholder="Select Product"
          onChange={this.setQRCode}
          required
        >
          <option value="">select</option>
          {this.props.products.map((product, i) =>
            <option key={i} value={product._id}>
              {product.productName}
            </option>
          )}
        </FormControl>
        <Barcode value={this.state.productid} />
      </div>
    );
  }
}

Upvotes: 2

Related Questions