06 JSX Expressions - biswajitsundara/react GitHub Wiki

To write a JavaScript expression within JSX we will have to surround the JavaScript code in { } brackets.

1. JS Expression For Data Types

String, number, array values can be represented as it is.

const DataTypes = () => {

  const bankname = "BisBank";
  const balance = 5000;
  const fruits = ["Apple", "Mango", "Strawberry"];

  return (
    <div>
      <h1>{bankname}</h1>
      <p>The bank name is {bankname}</p>
      <p>{balance}</p>
      <p>{fruits}</p>

      <p>{"Biswajit"}</p>
      <p>{30}</p>
      <p>{["savings", "current"]}</p>
    </div>
  );
};

export default DataTypes;

2. JS Expression For Boolean/Object

  • We can't write the boolean values within {} instead we need to add template literal {${variable_name}}
  • We can't write object value as it is within {} instead we can do this way {JSON.stringify(objectvariablename)} or access specific field
const BooleanObject = () => {

  const married = false;
  const address = {
    street: "12 Park Street",
    pin: 75012,
  };
  return (
    <div>
      <p>{`${married}`}</p>
      <p>{JSON.stringify(address)}</p>
      <p>{address.street}</p>
    </div>
  );
};

export default BooleanObject;

3. JS Expression Evaluation

We can have JSX expression for performing calculation/evaluation directly.

  • Here the numbers are added, or a random number is generated directly in JSX
  • Basically we can evaluate valid java script expressions within {}
  • We can have conditional check also, based on validProfile value it will display the message.
const ExpressionEval = () => {

  const validProfile = true;
  return (
    <div>
      <p>{5000 + 5000}</p>
      <p>{Math.random() * 10}</p>
      <p className="messages">
        {validProfile ? "valid profile" : "invalid profile"}
      </p>
    </div>
  );
};

export default ExpressionEval;

4. JS Expression For Attributes

  • We can specify the attributes id or name along with the tag e.g <h1 id="header>"
  • in JSX className attribute is used instead of class.
  • However in the DOM it will show as class because we know the JSX gets converted to Java script under the hood.
const ForAttributes = () => {

  const appName = "Bis Bank";
  const link = "https://google.com";

  return (
    <div>
      <h1 id="header">{appName}</h1>
      <p className="messages">Hello World</p>
      <a href={link}>Google.com</a>
    </div>
  );
};

export default ForAttributes;

5. JS Expression For Events

  • For events we can attach using the {functionName} e.g onClick={clickHandler}
  • Make sure you don't include the round brackets e.g e.g onClick={clickHandler()}
  • Because the round brackets will execute the function right away and it will error out.
const ForEvents = () => {

  function clickHandler() {
    console.log("Hello World");
  }

  return (
    <div>
      <button onClick={clickHandler}>Hello</button>
    </div>
  );
};

export default ForEvents;
⚠️ **GitHub.com Fallback** ⚠️