Description
I'm very new to React JS, which will probably show in my code. I'm trying to make a simple to-do app that will help me get my head around coding with React. The app should simply display "Complete" if a checkbox is checked and "Incomplete" if it isn't. However, the checkboxes aren't updating on click.
I think that the problem is to do with not understanding React logic, resulting in the Checkbox() function being called over and over with default variables (eg: checked == true).
Any advice would be appreciated!
Code and Examples
File tree (excluding node_modules folder):
.
├── package.json
├── package-lock.json
├── public
│ └── index.html
└── src
├── App.js
├── Checkbox.js
├── index.css
├── index.js
├── TableBody.js
├── TableHeader.js
└── Table.js
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>React App</title>
</head>
<body>
<div id="root"></div>
</body>
</html>
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import 'bootstrap/dist/css/bootstrap.min.css';
ReactDOM.render(<App />, document.getElementById('root'));
App.js
import { Component } from "react";
import Table from "./Table"
class App extends Component {
render() {
const tasks = [
{
status: "incomplete",
task: "Wash Dishes"
},
{
status: "complete",
task: "Pat Dog"
},
{
status: "incomplete",
task: "Study"
}
]
return (
<div>
<Table tasks={tasks}/>
</div>
)
}
}
export default App;
Table.js:
import TableHeader from "./TableHeader"
import TableBody from "./TableBody"
import { Component } from "react"
class Table extends Component {
render () {
const {tasks} = this.props
return (
<div className="table container">
<TableHeader />
<TableBody tasks={tasks}/>
</div>
)
}
}
export default Table
TableBody.js
import Checkbox from './Checkbox'
const TableBody = (props) => {
// takes the properties of the Table object and creates table rows by mapping
// elements in the array. Returns a table body.
const rows = props.tasks.map((row, index) => {
return (
<tr key={index}>
<td><Checkbox /></td>
<td>{row.task}</td>
</tr>
)
})
return <tbody>{rows}</tbody>
}
export default TableBody
TableHeader.js
const TableHeader = () => {
return (
<thead>
<tr>
<th>Status</th>
<th>Task</th>
</tr>
</thead>
)
}
export default TableHeader
Checkbox.js
const checkStatus = (checked) => {
var status = "Something's gone wrong."
if (checked) {
var status = "Complete"
} else if (checked == false) {
var status = "Incomplete"
} else {
}
return status
}
const Checkbox = () => {
const input = <input class="form-check-input" type="checkbox" checked></input>
const status = checkStatus(input.props.checked)
return (
<div class="custom-control custom-textbox">
{input}
<label>{status}</label>
</div>
)
}
export default Checkbox
Aucun commentaire:
Enregistrer un commentaire