0

I am programing my new website in a structure with nodejs, nextjs and expressjs. The problem is tho that I want to write a if statement inside of the HTML part which in that case it will write the if statement as normal html on the website:

const Admin = () => (

  <AdminLayout>

  <style global jsx>
  {
  `body {
    background: #eff0f3;
   }`
  }
  </style>  
    <div className="jumbotron" style={jumbotron}>

      if (1=1) {
      <h3>Please select a tool first.</h3>
    } else {
      <h3>Something is wrong :/ .</h3>
    }

    </div>
  </AdminLayout>
)

export default Admin

And the out put is just:

if (1=1) Please select a tool first. else Something is wrong :/ .

as HTML on the website. How would I do this but having the script actually being a script?

1 Answer 1

1

Next.js uses React that allows you to write something called jsx, which is what you're calling the "HTML part". You can write JavaScript expressions in jsx, but they need to be wrapper in {} brackets. Otherwise any JS code will actually just be interpreted as a text string in the rendered HTML. Check out the React Docs for Embedding Expressions in JSX.

There's lots of ways to do conditional rendering in React.

Here's one way to rewrite your code using {} to embed an expression and the ternary operator:

const Admin = () => (
  <AdminLayout>
    <style global jsx>{`
      body {
        background: #eff0f3;
      }
    `}</style>  
    <div className="jumbotron" style={jumbotron}>
      {1 == 1 ? (
        <h3>Please select a tool first.</h3>
      ) : (
        <h3>Something is wrong :/ .</h3>
      )}
    </div>
  </AdminLayout>
)

export default Admin
Sign up to request clarification or add additional context in comments.

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.