Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop inside map function using jsx format React JS

I need help in rendering my array I want to make a condition inside my map function. But somehow my transpiler is not the accepting and having parsing error Here is my code:

import { getGroups } from '../../actions/groupActions'
import { refreshToken } from '../../actions/authActions'
import { connect } from 'react-redux'
import _ from 'lodash'
import { Link } from "react-router"

class Group extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      groups: []
    };
  }

  componentWillMount(){
    this.props.getGroups().then(() => {
      console.log('this groups props: ', this.props)
      if(this.props.errors.code === 'UNAUTHORIZED'){
        this.props.refreshToken().then(() => {
          this.props.getGroups()
        })
      }
    })
  }

  render(){

    const groupArr =  _.valuesIn(this.props.groups)

    return (
      <div>
        <h1>Groups</h1>
        <table className="table table-responsive table-bordered table-condensed">
          <thead>
            <tr>
              <td>Name</td>
              <td>Queue</td>
              <td>Created At</td>
              <td>Execution Type</td>
              <td>Members</td>
              <td>Action</td>
            </tr>
          </thead>
          <tbody>
            {this.props.groups ? (groupArr.map((groups, i) => {
                return (
                  <tr key={i}>
                    <td>{groups.name}</td>
                    <td>{groups.queue}</td>
                    <td>{groups.createdAt}</td>
                    <td>{groups.executionType}</td>
                    <td>
                      {groups.members ? (groups.members.map((members, index) => {
                        {members.type === 'command' ? (
                          return (<div className="alert alert-success" role="alert" key={index}>{members._id}</div>)
                        ) : (
                          return (<div className="alert alert-danger" role="alert" key={index}>{members._id}</div>)
                        ) }
                      })) : (return ('No members found'))}
                    </td>
                    <td>
                      <Link className="btn btn-sm btn-warning" >
                        <i className="fa fa-pencil"></i>
                      </Link>
                      <button className="btn btn-sm btn-danger">
                              <i className="fa fa-trash-o"></i>
                      </button>
                      <button className="btn btn-sm btn-success">
                              <i className="fa fa-play-circle"></i>
                      </button>
                    </td>
                  </tr>
                )
            })) : (<tr>No records found</tr>)}
          </tbody>
        </table>
      </div>
    );
  }

}

Group.propTypes = {
  getGroups: React.PropTypes.func.isRequired,
  errors: React.PropTypes.object.isRequired,
  refreshToken: React.PropTypes.func
}

Group.contextTypes = {
  router: React.PropTypes.object.isRequired
}

function mapStateToProps(state) {
  return{
    groups: state.groupReducer.groups,
    links: state.groupReducer.links,
    errors: state.groupReducer.errors
  }
}

export default connect(mapStateToProps, { getGroups, refreshToken })(Group)

Here is the error:

SyntaxError: C:/Users/Frank/Projects/crun_fe/src/js/react/components/group/Group.js: Unexpected token (55:26)
  53 |                       {groups.members ? (groups.members.map((members, index) => {
  54 |                         {members.type === 'command' ? (
> 55 |                           return ({members._id})
     |                           ^
  56 |                         ) : (
  57 |                           return ({members._id})
  58 |                         ) }
like image 558
Frank Mendez Avatar asked Feb 07 '17 05:02

Frank Mendez


People also ask

Can we use loop inside JSX?

Using the Array map function is a very common way to loop through an Array of elements and create components according to them in React. This is a great way to do a loop which is a pretty efficient and is a tidy way to do your loops in JSX. It's not the only way to do it, but the preferred way.

How do you loop a map in react JS?

In React, the map() function is most commonly used for rendering a list of data to the DOM. To use the map() function, attach it to an array you want to iterate over. The map() function expects a callback as the argument and executes it once for each element in the array.

Can we use for loop instead of map in React?

So if your goal is just to render UI, a 'for' loop is fine. However, if your goal is to create a complex re-usable component, the preferred method is 'map': This method takes a callback function with three parameters: the current value while iterating, the current index and the array on which you iterate.

How do you write condition inside a map in react JS?

To use a condition inside map() in React:Call the map() method on an array. Use a ternary operator to check if the condition is truthy. The operator returns the value to the left of the colon if the condition is truthy, otherwise the value to the right is returned.


1 Answers

You are using the ternary operator in a wrong way, Syntax is:

condition ? expression :  expression

Both values should be expression but you are using return statement, that's why it is throwing the error.

If you want to return the result then use it in this way:

return a ? a+1 : 0;

Didn't run this code, just made some changes to solve your original problem, please check the proper closing of braces and tags, Try this:

{
    this.props.groups ? groupArr.map((groups, i) => {
        return (
            <tr key={i}>
                .....
                <td>
                    {
                        groups.members ? 
                            groups.members.map((members, index) => {
                                return members.type === 'command' ? 
                                    <div className="alert alert-success" role="alert" key={index}>{members._id}</div>
                                : 
                                    <div className="alert alert-danger" role="alert" key={index}>{members._id}</div>
                            }) 
                        :  <div>'No members found'</div>
                    }
                </td>
                .....
            </tr>
        )
    }) : <tr> No records found </tr>
}
like image 131
Mayank Shukla Avatar answered Oct 14 '22 21:10

Mayank Shukla