0

i am learning Reactjs while building a simple application. I know this is very basic and there are alot of answers for the same question available on stackoverflow. But i am unable to implement those maybe because of variable scopes. I would be grateful if someone is able to help me out with this.

My full code is pretty complex and irrelevant to the question. But please refer to this fiddle : Full Code. This will work in local server.

Relevant Code:

var localStore = {};
// localStore = {"f":{"symbol":"f","quantity":10,"pricePaid":136},"jnj":{"symbol":"jnj","quantity":30,"pricePaid":146}};

var SearchStock = React.createClass({
...
render: function() {
...
return ( // I tried map function in other ways too like [localstore].map and then get its values in similar way as i am getting below.
{/*localStore.map(function (l, i) {
  return <tr>
           <td>{Object.keys(l)[i].symbol}</td>
           <td>{Object.keys(l)[i].quantity}</td>
           <td>{Object.keys(l)[i].pricePaid}</td>
           <td>{Object.keys(l)[i].symbol}</td>
         </tr>
})*/}
{/*for(var x in localStorage){ // This is what i really want to do.
  return <tr>
           <td>{x.symbol}</td>
           <td>{x.quantity}</td>
           <td>{x.pricePaid}</td>
           <td>anything</td>
         </tr>
}*/}
{stocks.map(function(l) { // this works.
   console.log("in return stocks",JSON.stringify(stocks));
   return <tr>
            <td>{l[Object.keys(l)[0]]["name"]}</td>
            <td>{this.state.quantity}</td>
            <td>{this.state.pricePaid}</td>
            <td>{<input type="button" value="View Stock"/>}</td>
          </tr>
}, this)}

I don't know why map function didn't work as value in localStore and stocks is similar: stocks = [{only one key pair of localStore}]. I would appreciate any help or guidance i can get for this.

1 Answer 1

1

You should use Object.keys to get an array with the keys of localStore and iterate through it to display your data.

{Object.keys(localStore).map(function (key) {
          return <tr key={key}>
              <td>{localStore[key].symbol}</td>
              <td>{localStore[key].quantity}</td>
              <td>{localStore[key].pricePaid}</td>
              <td>{localStore[key].symbol}</td>
          </tr>
 })}

You were missing other things like

1º Provide a key to every child in the array.

2º Wrap your <tr> tags inside a <tbody>. <tr> cannot appear as a child of <table>

jsfiddle

Sign up to request clarification or add additional context in comments.

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.