Home > AI > Frontend > ReactJS >

React Intro

Step 1: setting up the environment

npx create-react-app {appName}

Step 2: install a Visual Studio Code plugin: ES7 React/Redux/GraphQL/React-Native snippets

Step 3: Example Code

Todo.js

import React from 'react'

export default function Todo({todo}) {
    return (
        <div>
            <label>
                <input type="checkbox" checked={todo.complete} onChange={()=>{}}/>
                {todo.name}
            </label>
            
        </div>
    )
}

TodoList.js

import React from 'react'
import Todo from './Todo'
export default function TodoList({todos}) {
    return (
       todos.map(todo => {
            return <Todo key={todo.id} todo={todo} />
       })
    )
}

App.js

import React, {useState, useRef} from "react";
import TodoList from "./TodoList";
const { v4: uuidv4 } = require('uuid');

function App() {
  const [todos, setTodos] = useState([])
  const todoNameRef = useRef()




  return (
    <>
      <TodoList todos={todos}/>
      <input ref={todoNameRef} type="text" />
      <button onClick={handleAdd}>Add </button>
      <button onClick={handleClear}>Clear</button>
      <div>0 left todolists</div>
    </>
    
  )

  function handleAdd(e) {
    const name = todoNameRef.current.value
    if (name === "") { return }
    setTodos(prevTodos => {
      return [...prevTodos, {id: uuidv4(), name: name, complete: false}]
    })
    todoNameRef.current.value = null
  }

  function handleClear(e) {

  }

}

export default App;

Leave a Reply