Full Stack Development

JSX and Components

by Tomas Trescak t.trescak@westernsydney.edu.au

JSX

Introduction

      body { padding: 16px; }
    

JSX

Fragments

      function Greeting() {
  return (
    <div>
      <h1>Hello, Developer!</h1>
      <p>
        Welcome to the wacky 
        world of React!
      </p>
    </div>
  );
}

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<Greeting />);
    

JSX

Elements and Components

      const ui = (
  <button><i class="trash" /> Bye</button>
)

const DeleteButton = () => (
  <button>
    <i class="ph ph-trash" /> Delete
  </button>
)

const Post = () => (
  <div>
    <h1>Post: Your post</h1>
    <p>Post text</p>
    <DeleteButton />
  </div>
)

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<Post />);
    

JSX

Expressions

      function MathGreeting() {
  const name = "Developer";
  const a = 6;
  const b = 10;
  return (
    <div>
      <h1>Hello, {name}!</h1>
      <p>Sum of {a} and {b} is {a+b}</p>
    </div>
  );
}
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<MathGreeting />);
    

JSX

Expressions

      function Expressions() {
  const a = "Developer";
  const b = Math.round(6 / 3);
  const c = <b>Hello</b>;
  const d = { a: 1 } // NO!
  const e = JSON.stringify(d)
  return (
    <ul>
      <li>{a}</li>
      <li>{b}</li>
      <li>{c}</li>
      <li>{e}</li>
    </ul>
  );
}
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<Expressions />);
    

JSX

👾 Expressions: Interactive Example

JSX

Interactive Components

    function Button(props: { 
    title: string, 
    message: string 
  }) {
  function clickHandler() {
    alert(props.message);
  }
  const background = props.message === 'No!' 
        ? 'red' : 'green';
  return( 
    <button 
      onClick={clickHandler}
      style={{ background }}>
      {props.title}
    </button>)
}

// React code to modify elements
const App = () => {
  return (
    <div>
      <Button title="Say Hi!" message="Hi!" />
      <br />
      <Button title="Say Ola!" message="No!" />
    </div>
  );
};
  

JSX

👾 Expressions: Interactive Example

Transpiling JSX

    type Props = { message: string }

function Message(props) {
  return <div>{props.message}</div>
}

function App() {
  return <Message message="Hello" />
}
  
    import React from 'react';

function Message(props) {
  return React.createElement('div', { message: props.message})
}

function App() {
  return React.createElement(Message, { message: "Hello" })
}
  

JSX

Fragments

      function Greeting() {
  return (
    <h1>Hello, Developer!</h1>
    <p>
      Welcome to the wacky 
      world of React!
    </p>
  );
}

render(<Greeting />)
    

JSX

Fragments

      

function Greeting() {
  return (
    <div>
      <h1>Hello, Developer!</h1>
      <p>
        Welcome to the wacky 
        world of React!
      </p>
    </div>
  );
}

render(<Greeting />)