0
this.state.obj= [{"listing_id":"1","listing_name":"A"},{"listing_id":"2","listing_name":"iima "},{"listing_id":"3","listing_name":"dsffgdf"}];

inside render function =>

{this.state.obj.map((name,index) => 
  <tr key={index}>
    <td key={index} onClick={this.openOptions.bind(this,name.listing_id)}>{name.listing_id}</td>
    <td key={name.listing_name}>{name.listing_name}</td>
    if(name.listing_id == openOptionsvar){
      <td key={index+1} >Edit</td>
    }
  </tr>
)}

i want display last td element if openOptionsvar value equals to listing_id of that row??

3 Answers 3

1

listing_id is a React.PropTypes.string. Check which propType is openOptionsvar (probably a React.PropTypes.number). I am afraid they are different properties so you have to convert any of them to the correspondent propType and in your condition use the strict equality comparison, doing for example (if openOptionsvar is number):

 if(Number(name.listing_id) === openOptionsvar){
   <td key={index+1} >Edit</td>
 }
Sign up to request clarification or add additional context in comments.

1 Comment

I liked, Number(name.listing_id) === openOptionsvar instead , name.listing_id == openOptionsvar.
0

You can write if condition within map as follows

class App extends React.Component {
  constructor() {
    super();
     this.state = {
          obj: [{"listing_id":"1","listing_name":"A"},{"listing_id":"2","listing_name":"iima "},{"listing_id":"3","listing_name":"dsffgdf"}]
     }
  }
  render() {
    var openOptionsvar = 2;
    return (
      <div>
      {this.state.obj.map((name,index) => {
      if(name.listing_id == openOptionsvar) {
        return <li>{name.listing_name}</li>
      }}
      )}
     </div> 
    )
  }
}
ReactDOM.render(<App/>, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>

Comments

0

While using any loop in React to render elements, you must use key attribute. And try to use ternary operator instead of for loop. The ternary operator is a substitute for an if statement in which both the if and else clauses assign different values to the same field, like so:

render() {
        var openOptionsvar = 2;
        return (
          <div>
          {this.state.obj.length>0 && this.state.obj.map((name,index) => {
            return name.listing_id == openOptionsvar? <li key={index}>{name.listing_name}</li>:null
          }
          )}
         </div> 
        )
      }
    }

Edit:
use Number(name.listing_id) === openOptionsvar in place of name.listing_id == openOptionsvar

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.