0

I want to set value="a" depending on the condition it meets. Button has no value attribute currently. How do I write this?I want like this <button value="a"> One </button>

const buttonValues = ["a", "b"]  

const addingValuesToButtons = () => {
   for (var i = 0; i < buttonValues.length; i++) {
      if(buttonValues[i] === "a") {
         //add attribute name and value to first two buttons
      }
      if(buttonValues[i] === "b"){
         //add attribute name and value to first three buttons
      }
   };

   return(
     <div>
      <button> One </button>
      <button> Two </button>
      <button> Three </button>
      <button> Four </button>
     </div>
   )
}
1
  • Use if(i<2) { instead. Commented Aug 13, 2018 at 7:55

2 Answers 2

1
const buttonValues = ["a", "b"]  

const addingValuesToButtons = () => {
   const buttons = [];
   for (var i = 0; i < buttonValues.length; i++) {
      if(buttonValues[i] === "a") {
         buttons.push({attr: 'foo', name: 'bar'});
      }
      if(buttonValues[i] === "b"){
         buttons.push({attr: 'baz', name: 'bar2'})
      }
   };

   return(
     <div>
      {buttons.map(button => {
        return <button attr={button.attr}>{button.name}</button>;
      })}
     </div>
   )
}
Sign up to request clarification or add additional context in comments.

1 Comment

yep, there was a missing closing bracket in map - sorry ;)
0

It will go like this:

<button value={this.buttonValues[0] == 'a'?this.buttonValues[0]:null}> One </button>

another netter approach is :

const buttonValues = [{value:"a",name:"One"}, {value:"b",name:"two"}]  

this.buttonValues.map(value => {<button value={value.value == 'a'? value.value:null}>{value.name}</button>}) ;

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.