React 18

Last Updated: 9/24/2023

React Component

  • React components can be created using a javascript function or a class. Function-based components are the preferred approach as they’re more concise and easier to write.
  • Following Pascal casing for naming components
  • .ts: typescript file extension
  • .tsx react components using typescript
  • We should describe what the UI is going to look like where we use the component.

JSX

  • JSX stands for JavaScript XML.
  • With JSX, we can easily describe the user interface of our application with HTML and JavaScript
  • Under the hood JSX gets compiled to JavaScript
  • It is a syntax that allows us to write components that combine HTML and JavaScript in a readable and expressive way, making it easier to create complex user interfaces
  • JSX to Javascript Compiler babeljs.io/repl

Message.tsx

function Message() {
  const name = "Ganesh";
  if (name) return <h1>Hello {name}</h1>;
  return <h1>Hello World</h1>;
}

export default Message;

App.tsx

import Message from "./Message";

function App() {
  return (
    <div>
      <Message></Message>
    </div>
  );
}

export default App;
  • ./ refers to current folder
  • We should always close our React components, or we'll get a compilation error. You can use self-closing tags also.
  • HMR: hot module replacement. monitors our files for changes. Whenever we make any changes, it will automatically refresh our page in the browser.

Add Dynamic Content

  • JSX allows us to easily create dynamic content.
  • To add content dynamically use {expression}. An expression is a piece of code that produces a value. Use any valid JavaScript expression which produces a value.
<h1>Hello {name}</h1>