0

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

1
  • 2
    Please check this doc page: reactjs.org/docs/… Commented Nov 10, 2019 at 16:41

2 Answers 2

4

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>
)
Sign up to request clarification or add additional context in comments.

Comments

3

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>
        )
      }

    }

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.