r/reactjs • • Aug 01 '18

Beginner's Thread / Easy Question (August 2018)

Hello! It's August! Time for a new Beginner's thread! (July and June here)

Got questions about React or anything else in its ecosystem? Stuck making progress on your app? Ask away! We’re a friendly bunch. No question is too simple. You are guaranteed a response here!

Want Help on Code?

  • Improve your chances by putting a minimal example on to either JSFiddle (https://jsfiddle.net/Luktwrdm/) or CodeSandbox (https://codesandbox.io/s/new). Describe what you want it to do, and things you've tried. Don't just post big blocks of code.
  • Pay it forward! Answer questions even if there is already an answer - multiple perspectives can be very helpful to beginners. Also there's no quicker way to learn than being wrong on the Internet.

New to React?

Here are great, free resources!

27 Upvotes

568 comments sorted by

View all comments

Show parent comment

1

u/ObjectiveLength Aug 02 '18

I believe I solved it. Since owerRef exists within the component's state, I can just pass value into owerRef.

class AddLineItemForm extends React.Component {
  nameRef = React.createRef();
  priceRef = React.createRef();
  payerRef = React.createRef();
  owerRef = React.createRef();

  handleChange = event => {
    var options = event.target.options;
    let value = [];

    for (var i = 0, l = options.length; i < l; i++) {
      if (options[i].selected) {
        value.push(options[i].value);
      }
    }
    this.owerRef = value;
    console.log(this.owerRef);
  };

  createLineItem = event => {
    //1. stop the form from submitting
    event.preventDefault();
    const lineitem = {
      name: this.nameRef.value.value,
      price: parseFloat(this.priceRef.value.value),
      payer: this.payerRef.value.value,
      ower: this.owerRef
    };

    this.props.addLineItem(lineitem);
    // refresh the form
    event.currentTarget.reset();
  };

2

u/NiceOneAsshole Aug 03 '18

Some functional advice -

Your handleChange event could be much more succinct.

handleChange = event => {
   this.owerRef = event.target.options.filter(option => option.selected);    
}

2

u/ObjectiveLength Aug 03 '18

Updated the below:

  handleChange = event => {
    this.owerRef = [].filter
      .call(event.target.options, o => o.selected)
      .map(o => o.value);
    console.log(this.owerRef);
  };

Working on adding keys to this.owerRef

2

u/swyx Aug 05 '18

cool, sorry i missed this one