js-libs

Background

  • FOSS library, made by Facebook
  • used for front-end work, building web apps
  • each class component has a render method
  • React uses JSX, an extended version of JS which allows for HTML tags to be used directly inside the quote (without quoting)

Tutorial

  • zum Erlernen, werde ich mich nach Tania’s Tutorial richten
    • sie erklärt React zuerst anhand einer statischen HTML-Seite
    • Facebook hat allerdings dieses Projekt-Template “Create React App”
      • npx create-react-app react-tutorial
      • cd react-tutorial && npm start

First component

import React, {Component} from 'react'
import ReactDOM from 'react-dom'
 
class App extends Component {
  render() {
      return (
          return <h1>Hello world!</h1>
      );
  }
}
 
ReactDOM.render(<App />, document.getElementById('root'))

ReactDOM

“Warning: ReactDOM.render is no longer supported in React 18. Use createRoot instead. Until you switch to the new API, your app will behave as if it’s running React 17. Learn more: switch-to-createroot

Create React app: Installation


Class Components vs Simple (Function) Components

class ClassComponent extends Component {
  render() {
    return <div>Example</div>
  }
}
const SimpleComponent = () => {
  return <div>Example</div>
}

Creating custom HTML elements

import React, { Component } from 'react'
 
class Table extends Component {
    render() {
        return (
            <table>
                <thead>
                    <tr>
                        <th>Name</th>
                        <th>Job</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td>Charlie</td>
                        <td>Janitor</td>
                    </tr>
                    <tr>
                        <td>Mac</td>
                        <td>Bouncer</td>
                    </tr>
                </tbody>
            </table>
        )
    }
}
 
export default Table
import React, { Component } from 'react'
import Table from './Table'
 
class App extends Component {
    render() {
        return (
            <div className="container">
                <Table />
            </div>
        )
    }
}

Props

Instead of hard-coding the data, we’re pulling it in from somewhere else, based on the state of the application.

To render them, we can access them through the element’s this.props. We can then iterate over it and map each entry to a new variable with a place in the DOM.

const TableBody = (props) => {
    const rows = props.characterData.map((row, index) => {
        return (
            <tr key={index}>
                <td>{row.name}</td>
                <td>{row.job}</td>
            </tr>
        )
    })
 
    return <tbody>{rows}</tbody>
}