tegradite
tegradite

Reputation: 69

can't use if/else inside react render method

I am using React with Ant Design, but this is only a react issue.

I have a code like this:

  {
    title: "Group",
    dataIndex: "group",
    key: "group",
    render: text => (
     <a> {text} </a>
    )
  }

Not the render: text => () which allows me to use html inside a js function (or jsx?)

but, if I try to put if/else logic I get always an error.

Right now I am using something stupid like this:

render: texts => (
  <span>
     {[""].map(text => {
      if(texts.includes(":")) {
       return (<b> {texts} </b>)
      }
    return (<a> {texts} </a>)
  })}
</span>

The questions is, is there a way to do it without using [""].map() and why won't simple if/else work

Upvotes: 0

Views: 1666

Answers (2)

Aprillion
Aprillion

Reputation: 22322

Why it's not possible:

An equivalent expression, using a conditional operator to replace if:

render: texts => (
  <span>
     {texts.includes(":")
       ? <b>{texts}</b>
       : <a>{texts}</a>
     }
  </span>
)

Upvotes: 4

giuseppedeponte
giuseppedeponte

Reputation: 2391

You cannot use if/else inside JSX, but you can either use a ternary expression inside the JSX or an if/else condition inside your function before returning some JSX. Here is an example of both:

    {

      render: texts => (
        <span>
          { 
            texts.includes(":")
              ? <b> {texts} </b>
              : <a> {texts} </a>
          }
        </span>
      ),

      otherRender: texts => {
        if (texts.includes(":")) {
          return (
            <span><b> {texts} </b></span>
          )
        }
        return (
          <span><a> {texts} </a></span>
        )
      }

    }

Upvotes: 3

Related Questions