javascript - How do I add a condition to react material-ui elements? - Stack Overflow

I am building a generic data table using react and material-ui.My background is c# and java, and earl

I am building a generic data table using react and material-ui. My background is c# and java, and early javascript, so I'm having issues w/the syntax in reactjs.

Specifically I have the following code:

  <TableRow>
    {formColumns.map((x, i) =>
      ---WRAP THE FOLLOWING IN A CONDITION
      <TableHeaderColumn key={`thc-${i}`}>
        <div
          style={{
            display: "flex",
            alignItems: "center"
          }}
          onClick={() => handleSort(x.name)}
        >
          <span>{x.label}</span>
          {columnToSort === x.name ? (
            sortDirection === "asc" ? (
              <ArrowDownwardIcon fontSize='small' />
            ) : (
                <ArrowUpwardIcon fontSize='small' />
              )
          ) : null}
        </div>
      </TableHeaderColumn>
      ---WRAP THE ABOVE IN A CONDITION
    )}
    <TableHeaderColumn>
      <CheckboxMenu formColumns={formColumns} />
    </TableHeaderColumn>
  </TableRow>

The object I'm using for the 'map' is defined as follows:

{    id: {
      name: 'id',
      displayColumn: false,
      displayOrder: 1,
    },
    firstName: {
      name: 'firstName',
      label: 'First name*',
      requiredErrorMsg: 'First name is required',
      displayColumn: true,
      displayOrder: 2,
    },
 ...
}

I want to wrap the above elements in a condition that looks like this:

if (x.displayColumn === true)
{
  ---PUT THE ABOVE CODE BETWEEN THE WRAP COMMENTS HERE
}
else
{
  do nothing
}

Seems like an easy thing to do right? It is in any other language I've used. But reactjs keeps giving me syntax errors. Can someone put the above code together correctly and explain to me what I'm doing wrong? I can't find an answer to this issue anywhere. Help is much appreciated!

EDITED TO ADD THE FOLLOWING:

When I attempt to do this:

  <TableRow>
    {formColumns.map((x, i) =>
    {
      x.displayColumn === true ? (

        <TableHeaderColumn key={`thc-${i}`}>
          <div
            style={{
              display: "flex",
              alignItems: "center"
            }}
            onClick={() => handleSort(x.prop)}
          >
            <span>{x.label}</span>
            {columnToSort === x.name ? (
              sortDirection === "asc" ? (
                <ArrowDownwardIcon fontSize='small' />
              ) : (
                  <ArrowUpwardIcon fontSize='small' />
                )
            ) : null}
          </div>
        </TableHeaderColumn>
      ) : (null) <--ERROR
    }
    )}
    <TableHeaderColumn>
      <CheckboxMenu formColumns={formColumns} />
    </TableHeaderColumn>
  </TableRow>

I get this error:

"(ESLint) Expected an assignment or function call and instead saw an expression."

Before someone mentions the (null), I've tried (''), ("") and anything else. I still get the same error. The fact is I'd rather use an if statement, since there IS NO ELSE.

I am building a generic data table using react and material-ui. My background is c# and java, and early javascript, so I'm having issues w/the syntax in reactjs.

Specifically I have the following code:

  <TableRow>
    {formColumns.map((x, i) =>
      ---WRAP THE FOLLOWING IN A CONDITION
      <TableHeaderColumn key={`thc-${i}`}>
        <div
          style={{
            display: "flex",
            alignItems: "center"
          }}
          onClick={() => handleSort(x.name)}
        >
          <span>{x.label}</span>
          {columnToSort === x.name ? (
            sortDirection === "asc" ? (
              <ArrowDownwardIcon fontSize='small' />
            ) : (
                <ArrowUpwardIcon fontSize='small' />
              )
          ) : null}
        </div>
      </TableHeaderColumn>
      ---WRAP THE ABOVE IN A CONDITION
    )}
    <TableHeaderColumn>
      <CheckboxMenu formColumns={formColumns} />
    </TableHeaderColumn>
  </TableRow>

The object I'm using for the 'map' is defined as follows:

{    id: {
      name: 'id',
      displayColumn: false,
      displayOrder: 1,
    },
    firstName: {
      name: 'firstName',
      label: 'First name*',
      requiredErrorMsg: 'First name is required',
      displayColumn: true,
      displayOrder: 2,
    },
 ...
}

I want to wrap the above elements in a condition that looks like this:

if (x.displayColumn === true)
{
  ---PUT THE ABOVE CODE BETWEEN THE WRAP COMMENTS HERE
}
else
{
  do nothing
}

Seems like an easy thing to do right? It is in any other language I've used. But reactjs keeps giving me syntax errors. Can someone put the above code together correctly and explain to me what I'm doing wrong? I can't find an answer to this issue anywhere. Help is much appreciated!

EDITED TO ADD THE FOLLOWING:

When I attempt to do this:

  <TableRow>
    {formColumns.map((x, i) =>
    {
      x.displayColumn === true ? (

        <TableHeaderColumn key={`thc-${i}`}>
          <div
            style={{
              display: "flex",
              alignItems: "center"
            }}
            onClick={() => handleSort(x.prop)}
          >
            <span>{x.label}</span>
            {columnToSort === x.name ? (
              sortDirection === "asc" ? (
                <ArrowDownwardIcon fontSize='small' />
              ) : (
                  <ArrowUpwardIcon fontSize='small' />
                )
            ) : null}
          </div>
        </TableHeaderColumn>
      ) : (null) <--ERROR
    }
    )}
    <TableHeaderColumn>
      <CheckboxMenu formColumns={formColumns} />
    </TableHeaderColumn>
  </TableRow>

I get this error:

"(ESLint) Expected an assignment or function call and instead saw an expression."

Before someone mentions the (null), I've tried (''), ("") and anything else. I still get the same error. The fact is I'd rather use an if statement, since there IS NO ELSE.

Share Improve this question edited Jul 4, 2020 at 13:46 Andrew H asked Jul 4, 2020 at 13:31 Andrew HAndrew H 4632 gold badges9 silver badges27 bronze badges 1
  • What error does it give or are you using class ponent or functional ponent? – tcf01 Commented Jul 4, 2020 at 13:37
Add a ment  | 

3 Answers 3

Reset to default 3

You were missing the return statement

<TableRow>
  {formColumns.map((x, i) => {
    // return statement here
    return (
      x.displayColumn === true && (
        <TableHeaderColumn key={`thc-${i}`}>
          <div
            style={{
              display: "flex",
              alignItems: "center",
            }}
            onClick={() => handleSort(x.prop)}
          >
            <span>{x.label}</span>
            {columnToSort === x.name ? (
              sortDirection === "asc" ? (
                <ArrowDownwardIcon fontSize="small" />
              ) : (
                <ArrowUpwardIcon fontSize="small" />
              )
            ) : null}
          </div>
        </TableHeaderColumn>
      )
    );
  })}
  <TableHeaderColumn>
    <CheckboxMenu formColumns={formColumns} />
  </TableHeaderColumn>
</TableRow>;

The syntax is as follows

<TableRow>
  {formColumns.map((x, i) => {
    return <div>Something</div>
  })}
</TableRow>

OR

{formColumns.map((x, i) => (
    <div>Something</div>
))}

Because () => { return smthg; } is equivalent to () => (smthg) or () => smthg and you have to return something from the .map callback to get your JSX evaluated.

Btw. conditional statement in React is just && due to JS specifics.

Because, in the code flag && someFunc() someFunc never gets called if flag is false. Therefore, doing this way your JSX would never get evaluated and never rendered.

You can use ternary operator to decide the condition.

EX:

<TableRow>
  {formColumns.map((x, i) => (
    x.displayColumn
      ? (
        // PUT THE ABOVE CODE BETWEEN THE WRAP COMMENTS HERE
      )
      : null
    )
  )}
  <TableHeaderColumn>
    <CheckboxMenu formColumns={formColumns} />
  </TableHeaderColumn>
</TableRow>

If anyone is still looking for another solution, on Material UI 4 this works for me

const [activeElement, setactiveElement] = useState(false);


const classes = useStyles({activeElement});//Sent as object

return (
<div onMouseEnter={() => setHoverActive(true)} onMouseLeave={() => setHoverActive(false)} className={classes.card}>

</div>
);

/* Outside the export element */

const useStyles = makeStyles((theme) => ({
    card: {
        backgroundColor: ({activeElement}) => activeElement ? "red": "blue",    
    }

})

In this case, when you hover, the background color change... This base on conditions of true/false. A simple example for conditions in Material UI, hope this is use full for someone

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744852417a4597203.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信