0
votes

I couldn't find what is wrong, can't see which line has problem in jsbin. http://jsbin.com/bewigabomi/edit?js,console,output

class HelloWorldComponent extends React.Component {

  constructor(){
    super()
    this.handleChange = this.handleChange.bind(this)
  }

  handleChange(e){
    console.log(e.target.value)
  }

  render() {
    const data = {
      "fruits":[
        {"name":"banana","value":true},
        {"name":"watermelon","value":false},
        {"name":"lemon","value":true},
      ]
    }
    return (      
        {data.fruits.map(obj => 
         <div>
           <label>{obj.name}</label>
           <input onChange={(e) => this.handleChange(e)} type="checkbox" defaultChecked={obj.true}/>
         </div>
         )}
    );
  }
}

React.render(
  <HelloWorldComponent/>,
  document.getElementById('react_example')
);

Tried for more than 15min, couldn't spot the problem, need help!

3

3 Answers

1
votes

Moved the constant outside of the class and create a _drawlayout method instead and it worked.

const data = {
  "fruits":[
    {"name":"banana","value":true},
    {"name":"watermelon","value":false},
    {"name":"lemon","value":true},
  ]
}

class HelloWorldComponent extends React.Component {

  constructor(){
    super()
    this.handleChange = this.handleChange.bind(this)
  }

  handleChange(e){
    console.log(e.target.value)
  }

  _drawLayout() {
    return data.fruits.map(obj => {
      return(
        <div>
          <label>{obj.name}</label>
          <input onChange={e => this.handleChange(e)} type="checkbox" defaultChecked={obj.true}/> 
        </div>
      )
    })
  }

  render() {
    return (      
        <div>
          {this._drawLayout()}
        </div>
    );
  }
}

React.render(
  <HelloWorldComponent name="Joe Schmoe"/>,
  document.getElementById('react_example')
);

Edit: The map() method needs to have a return.

0
votes

You need to wrap your map function like

return (
    <div>{data.fruits.map(obj => (
            <div>
                <label>{obj.name}</label>
                <input onChange={(e) => this.handleChange(e)} type="checkbox" defaultChecked={obj.true} />
            </div>
        )
    )}</div>
);

You can return single component but map return array;

0
votes

I think you're missing a left parenthesis, and also map must have a return clause:

return (      
    {data.fruits.map(obj => 
     //Your are missing this parenthesis and the return instruction
     return (
       <div>
         <label>{obj.name}</label>
         <input onChange={(e) => this.handleChange(e)} type="checkbox" defaultChecked={obj.true}/>
       </div>
     )}
);