I create a table I get data from the database using the backend I just want to show the output of the table on the page the output will not be visible
This is the code of my table.js
//import Data from './TextForm';
function Table(props) {
console.log('type ', typeof (props.Data));
console.log('data ', props.Data)
return (
<table>
<thead>
<tr>
<th>Text No</th>
<th>TextArea</th>
</tr>
</thead>
<tbody>
{props.Data ?
Object.entries(props.Data).map((key,value)=> {
console.log('Key',key);
{
<tr key={value}>
<td>{key.textId}</td>
<td>{key.textArea}</td>
</tr>
}
})
: null
}
</tbody>
</table>
)
}
export default Table;
this is props. data where I get the data and define prop. data I get data from the backend I connected the frontend for getting and storing data
Edit
function TextForm(props) {
const [text, setText] = useState('');
const [submittext,setsubmittext]=useState(null);
const [Data,setData]=useState([]);
const handleOnClickUpperCase = () => {
var newText = text.toUpperCase();
setText(newText);
}
const handleOnClickLowerCase = () => {
var newText = text.toLowerCase();
setText(newText);
}
const handleOnChange = (e) => {
setText(e.target.value);
}
const handleOnPreview = (e) => {
e.preventDefault();
setsubmittext(text);
// console.log(text);
const ROOT_URL='https://localhost:7113/';
var formData={
Textarea:text
}
axios.post(`${ROOT_URL}api/demo-text`, formData, {
headers: {"Access-Control-Allow-Origin": "*", 'Content-Type': 'application/json'}
})
.then(function (response) {
console.log('successs')
//handle success
setData(response);
console.log('response ',Data);
})
.catch(function (response) {
console.log('error')
//handle error
console.log(response);
})
}
return (
<>
<div className="container">
<h1>{props.title}</h1>
<p>Enter Text Here:</p>
<div className="mb-3">
<textarea className="form-control" value={text} onChange={handleOnChange} id="mybox" rows="8"></textarea>
</div>
<Table Data={Data} />
{text === text.toLowerCase() ? <button className="btn btn-primary" onClick={handleOnClickUpperCase}>Convert to Upper Case</button> : <button className="btn btn-primary" onClick={handleOnClickLowerCase}>Convert to Lower Case</button>}
<button className="btn btn-primary mx-3" onClick={handleOnPreview}>submit</button>
</div>
<hr></hr>
<div className="container my-4" >
<h1>{props.sum}</h1>
<p>Text Word {text.split(" ").length} and Character is {text.length}</p>
<p>{0.008 * text.split(" ").length} Minutes to Read</p>
</div>
<hr></hr>
<div className="container my-4">
<h2>Preview Your Text</h2>
<p>{submittext}</p>
</div>
</>
)
}
the output of prop.data
here have iterator objects array so pls try the following the code see I created an example as your same array object as you shared img pls find an example here link.
import React from "react";
import ReactDOM from "react-dom";
const Data = {
data: {
result: [
{ textId: 1, textarea: "test" },
{ textId: 2, textarea: "1234" },
{ textId: 3, textarea: null },
{ textId: 4, textarea: null },
]
}
};
function Table(props) {
console.log("type ", typeof props.Data);
console.log("data ", props.Data);
return (
<table>
<thead>
<tr>
<th>Text No</th>
<th>TextArea</th>
</tr>
</thead>
<tbody>
{props?.Data?.data?.result?.map((item) => (
<>
<tr key={item.textId}>
<td>{item.textId}</td>
<td>{item.textarea}</td>
</tr>
</>
))}
</tbody>
</table>
);
}
function App() {
return (
<>
<Table Data={Data} />
</>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
So you have to iterate over props.Data.data.result instead of props.Data, You don't need the Object.entries(),
and make the initial value of the Data = {} instead of [].
const [Data, setData] = useState({});
In the conditional JSX code, you need to check if the object has keys or not, and you don't need Object.entries method, just go with props.Data.data.result.map(), Also you have to return tr from the map method as #Usama mentioned.
{Object.keys(props.Data).length ?
props.Data.data.result.map((key,value)=> {
return (<tr key={value}>
<td>{key.textId}</td>
<td>{key.textArea}</td>
</tr>)
})
: null
}
Related
I'm working on a react project where the user needs to fill out a form, and according to the "Number of Credits" input - a table should be rendered with some of its rows possibly hidden. My idea was to to set up an isHidden property in the table objects and switch it according to the user input. Then, render only the rows where isHidden = false.
For some reason it's not working, the table keep being rendered as a whole, regardless to the input. I also tried to console.log the rows object, and the isHidden is not changing. Does anybody have an idea?
Here is my code:
App.js:
import Form from './components/Form'
import { useState } from 'react'
import TableDisplay from './components/TableDisplay'
import Banner from './components/Banner'
const App = () => {
const [showBanner, setShowBanner]=useState(false)
const [FormData, setFormData] = useState([
{
id:1,
name:'',
credits:'',
}
])
const [rows, setRows] = useState([
{
id:1,
description:'',
semester:'',
prefix:'ENG',
number:'368/371',
grade:'',
editing:'',
isHidden:false,
},
{
id:2,
description:'',
semester:'',
prefix:'',
number:'',
grade:'',
editing:'',
isHidden:false,
},
{
id:3,
description:'',
semester:'',
prefix:'',
number:'',
grade:'',
editing:'',
isHidden:false,
},
])
const getFormInfo = (info) => {
const id = Math.floor(Math.random() * 10000) + 1
const newName = {id,...info}
setFormData([newName]);
const num = info.credits;
if (num > 40 && num < 70) {
setRows(rows.map((row) =>
row.id===3 ? {isHidden:!row.isHidden}: row
))
}
else if (num>70) {
setRows(rows.map((row) =>
row.id===3 || rows.id===2 ? {isHidden:!row.isHidden}: row
))}
console.log(rows);
}
return (
<>
<Form onAdd={getFormInfo}
onAdd2={() => setShowBanner(!showBanner)
}
/>
{showBanner ? <Banner FormData={FormData}/> : null}
{showBanner ? <TableDisplay rows={rows}/>: null}
</>
);
}
export default App;
Form.js:
import { useState } from "react"
const Form = ({ onAdd,onAdd2}) => {
const[name, setName] = useState('')
const[credits, setCredits] = useState('')
const onSubmit = (e) => {
e.preventDefault();
onAdd({name,credits})
setName('');
setCredits('');
}
return (
<form onSubmit={onSubmit} >
<div className="mb-3">
<label className="form-label">Student Name:</label>
<input value={name}
onChange={(e) =>
setName(e.target.value)}
type="text"
className="form-control"
id="exampleInputEmail1"
aria-describedby="emailHelp"/>
</div>
<div className="mb-3">
<label className="form-label">Total Transfer Credits:</label>
<input value={credits}
onChange={(e) =>
setCredits(e.target.value)}
type="number"
className="form-control"
id="exampleInputPassword1"/>
</div>
<button onClick={onAdd2}
type="submit" className="btn btn-primary">Submit</button>
</form>
)
}
export default Form
TableDisplay.js:
import TableRows from "./TableRows"
const TableDisplay = ({rows, onDelete}) => {
return (
<div>
<table className="table table-striped">
<thead>
<tr>
<th scope="col">ID</th>
<th scope="col">Description</th>
<th scope="col">Semester</th>
<th scope="col">Prefix</th>
<th scope="col">Number</th>
<th scope="col">Grade</th>
<th scope="col">Editing</th>
</tr>
</thead>
<tbody>
{rows.map((row) => {
return <TableRows
key={row.id}
row={row}
/>
})}
</tbody>
</table>
</div>
)
}
export default TableDisplay
TableRows.js:
import React from 'react'
const TableRows = ({row}) => {
return (
<>
<tr>
<td scope="row">{row.id}</td>
<td>{row.description}</td>
<td>{row.semester}</td>
<td>ENG</td>
<td>368/371</td>
<td>{row.grade}</td>
<td><button type="button" className="btn btn-warning">Edit</button></td>
</tr>
</>
)
}
export default TableRows
Thanks!
import React , {useState, useEffect} from 'react'
import styles from './Statewise.css';
const Statewise = () => {
const [data, setData]=useState([]);
const getCData = async () => {
const res = await fetch('https://api.covid19india.org/data.json');
const actualData = await res.json();
console.log(actualData.Statewise);
setData(actualData.Statewise);
}
useEffect(() => {
getCData();
}, [])
return (
<div className="bts">
<div className="container-fluid mt-5">
<div className="main-heading">
<h1 className="mb-5">
<span className="font-weight-bold">INDIA COVID 19 TRACKER</span>
</h1>
</div>
<div className="table-responsive">
<table className="table table-hover">
<thead className="thead-dark">
<tr>
<th>States</th>
<td>Confirmed</td>
<td>recovered</td>
<td>death</td>
<td>active</td>
<td>updated</td>
</tr>
</thead>
<tbody>
{
data.map((curElem) => {
return(
<tr key={curElem.id}>
<th>{curElem.state}</th>
<td>{curElem.Confirmed}</td>
<td>{curElem.recovered}</td>
<td>{curElem.deaths}</td>
<td>{curElem.active}</td>
<td>{curElem.lastupdatedtime}</td>
</tr>
)
})
}
</tbody>
</table>
</div>
</div>
</div>
)
}
export default Statewise;
Not able to extract values from the api.
I have tried data && data.map(... this is also not working.
I have tried adding the load and error methods but then also the main data from the api id not displayed.
please suggest solutions .
Your actualData does not contain Statewise field but it does contain statewise (See difference in s in both fields)
So to solve this just replace Statewise with statewise
const getCData = async () => {
const res = await fetch('https://api.covid19india.org/data.json');
const actualData = await res.json();
setData(actualData.statewise);
}
When you use data in you HTML you can make a conditional statement to be sure that your data are loaded.
For exemple :
{
data ? data.map((curElem) => {
return(
<tr key={curElem.id}>
<th>{curElem.state}</th>
<td>{curElem.Confirmed}</td>
<td>{curElem.recovered}</td>
<td>{curElem.deaths}</td>
<td>{curElem.active}</td>
<td>{curElem.lastupdatedtime}</td>
</tr>
)
: <p> No data available </p>
})
}
hello iam following mosh hamedani course at some point i got stuck in uploading data in table
this is my table where title and genre is uploading where in stock and rate these are number not string are not uploading here is my table body
class TableBody extends Component {
render() {
const {data,columns} = this.props
console.log({data,columns})
return ( <tbody>
{data.map(item => <tr key={item._id}>
{columns.map(column => <td key={item._id + (column.path || column.key)}>{_.get(item,column.path)}</td>)}
</tr>
)}
</tbody>
);
}
}
data and columns are coming from movietable component here is the code
class MovieTable extends Component {
columns =[
{ path:'title',label:'Title'},
{ path:'genre.name',label:'Genre'},
{ path:'numberInstock',label:'stock'},
{ path:'dailyReantalRate',label:'Rate'},
{ key: 'like' },
{key: 'delete' }
];
render() {
const {movies, onDelete,onSort ,onLike,sortColumn,onAdd,deleted} = this.props;
return (
<table className="table">
<TableHeader columns={this.columns} sortColumn={sortColumn} onSort={onSort}/>
<TableBody data={movies} columns={this.columns}/>
<tbody>
{movies.map((movie) => (
<tr key={movie._id}>
<td>{movie.title}</td>
<td>{movie.genre.name}</td>
<td>{movie.numberInStock}</td>
<td>{movie.dailyRentalRate}</td>
<td>
{" "}
<Like
liked={movie.liked}
onClick={() => onLike(movie)}
/>{" "}
</td>
<td
onClick={() => onDelete(movie._id)}
className="btn btn-danger btn-outline-warning btn-sm active "
>
Remove
</td>
</tr>
))}
</tbody>
<tbody>
{deleted.map((movie) => (
<tr key={movie._id}>
<td>{movie.title}</td>
<td>{movie.genre.name}</td>
<td>{movie.numberInStock}</td>
<td>{movie.dailyRentalRate}</td>
<td>
{" "}
<Like />{" "}
</td>
<td
onClick={() => onAdd (movie._id)}
className="btn btn-danger btn-outline-primary btn-sm active "
>
ADD
</td>
</tr>
))}
</tbody>
</table>
);
}
}
movies from props coming from its parent movies component here is movies component code
class Movies extends Component {
state = {
movies:[],
deleted: [],
genres:[],
pageSize: 9,
currentPage:1,
sortColumn:{
path:'title',
order:'asc'
}
};
componentDidMount(){
const genres =[{ _id:"",name:'All Genres'},...getGenres()]
this.setState({
movies:getMovies(),
genres
})
}
handleDelete = (_id) => {
const movie = this.state.movies.find((x) => x._id === _id);
this.setState({ deleted: [...this.state.deleted, movie] });
this.setState({ movies: this.state.movies.filter((x) => x._id !== _id) });
};
handleLike = (m) => {
const movies = [...this.state.movies];
const index = movies.indexOf(m);
movies[index] = { ...movies[index] };
movies[index].liked = !movies[index].liked;
this.setState({ movies });
};
handleReinstate = (_id) => {
const movie = this.state.deleted.find((movie) => movie._id === _id);
this.setState({ movies: [...this.state.movies, movie] });
this.setState({
deleted: this.state.deleted.filter((movie) => movie._id !== _id),
});
};
handleGenreSelect = genre => {
this.setState({selectedGenre:genre, currentPage:1})
}
handleSort= sortColumn =>{
this.setState({sortColumn});
}
render() {
const { pageSize,currentPage,sortColumn,selectedGenre,movies:allMovies,deleted} = this.state;
const filtered = selectedGenre && selectedGenre._id ? allMovies.filter(m=>m.genre._id === selectedGenre._id ): allMovies;
const sorted = _.orderBy(filtered, [sortColumn.path],[sortColumn.order]);
const movies = paginate(sorted,currentPage,pageSize)
return (
<div className="row">
<div className="col-2">
<ListGroup items={this.state.genres} selectedItem={this.state.selectedGenre} onItemSelect={this.handleGenreSelect}/>
</div>
<div className="col">
<div className={this.getbadgesClasses()}> <p>there are {filtered.length} movies in our data base</p> </div>
<MovieTable
movies={movies}
onSort={this.handleSort}
onDelete={this.handleDelete}
onLike={this.handleLike}
deleted={deleted}
onAdd={this.handleReinstate}/>
<Pagination
itemCount={filtered.length}
pageSize={pageSize}
sortColumn={sortColumn}
onPageChange={this.handlePageChange}
currentPage={currentPage}
/>
</div>
</div>
);
}
getbadgesClasses() {
let classes = " badge m-2 badge-";
classes += this.state.movies.length === 0 ? "warning" : "primary";
return classes;
}
handlePageChange = (page) => {
this.setState({currentPage: page})
};
}
this is my console.log
i have give aerong path to Columns array its like spelling mistake in path
I'm trying to display data after fetching it, but that does not work :
import React, { Component } from "react";
import { Table, Button, ButtonToolbar } from "react-bootstrap";
const URL = "http://localhost:51644/api/";
let passedAthleteId = 0;
let passedAthleteSessionId = 0;
class AthleteTrainingSession extends Component {
constructor(props) {
super(props);
this.state = {
athleteTrainingSession: [],
discussions: [],
warmups: [],
workouts: [],
stretchings: [],
};
}
componentDidMount() {
this.fetchAthleteTrainingSession();
}
componentDidUpdate() {
this.fetchAthleteTrainingSession();
}
fetchAthleteTrainingSession = () => {
fetch(URL + `Coaches/4/Athletes/1/AthleteSessions/4`)
.then((response) => response.json())
.then((data) => {
this.setState({
athleteTrainingSession: data,
});
});
};
render() {
const {
athleteTrainingSession,
discussions,
warmups,
workouts,
stretchings,
} = this.state;
passedAthleteId = this.props.match.params.athleteId;
passedAthleteSessionId = this.props.match.params.athleteSessionId;
this.discussions = this.state.athleteTrainingSession.Discussions;
this.warmups = this.state.athleteTrainingSession.Warmups;
this.workouts = this.state.athleteTrainingSession.Workouts;
this.stretchings = this.state.athleteTrainingSession.Stretchings;
console.log(athleteTrainingSession);
console.log(this.warmups);
return (
<React.Fragment>
<div>
<h2 className="mt-2">
Programme d'entraînement :{" "}
{athleteTrainingSession.TrainingProgramName}
</h2>
<h4>
Séance d'entraînement : {athleteTrainingSession.TrainingSessionName}
</h4>
</div>
<div>
<ButtonToolbar>
<Button variant="primary">Ajouter</Button>
<Button variant="secondary">Discussion</Button>
</ButtonToolbar>
<h4>Échauffement</h4>
<Table className="mt-4" striped bordered hover size="sm">
<thead>
<tr className="d-flex">
<th className="col-6">Exercice</th>
<th className="col-6">Options</th>
</tr>
</thead>
<tbody>
{warmups.map((warm) => (
<tr className="d-flex" key={warm}>
<td className="col-6">{warm.ExerciseName}</td>
<td className="col-6">
<ButtonToolbar>
<Button className="mr-2" variant="info">
Modifier
</Button>
<Button className="mr-2" variant="danger">
Supprimer
</Button>
</ButtonToolbar>
</td>
</tr>
))}
</tbody>
</Table>
</div>
</React.Fragment>
);
}
}
export default AthleteTrainingSession;
athleteTrainingSession contains the fetched data, and warmups is a sub-object for athleteTrainingSession.
When I console.log(warmups), I can see that it does contain data, but I cannot display it in the table.
athleteTrainingSession contains the fetched data, and warmups is a sub-object for athleteTrainingSession.
When I console.log(warmups), I can see that it does contain data, but I cannot display it in the table.
I think you have misconception of using state in component.
You're able to console the warmups because in your code you console.log(this.warmups), but you render the map with this.state.warmups
you should setState all of the data that you get from fetch, i.e:
fetchAthleteTrainingSession = () => {
fetch(URL + `Coaches/4/Athletes/1/AthleteSessions/4`)
.then((response) => response.json())
.then((data) => {
this.setState({
athleteTrainingSession: data,
warmups: data.Warmups,
workouts: data.Workouts,
discussions: data.Discussions,
stretchings: data.Stretchings,
});
});
};
by doing this way, now you can access the warmups data from this.state.warmups then render it
render() {
const {
athleteTrainingSession,
discussions,
warmups,
workouts,
stretchings,
} = this.state;
return (
<React.Fragment>
...
{warmups.map((warm) => (
<tr className="d-flex" key={warm}>
<td className="col-6">{warm.ExerciseName}</td>
<td className="col-6">
<ButtonToolbar>
<Button className="mr-2" variant="info">
Modifier
</Button>
<Button className="mr-2" variant="danger">
Supprimer
</Button>
</ButtonToolbar>
</td>
</tr>
))}
...
</React.Fragment>
)
}
I'm new to react and learning hooks. I found examples online that im converting to use hooks as practice but running into an issue with one. The example i'm converting, I can't figure out why the "Remove" button for function handleRemoveSpecificRow on the table row doesn't work. It should remove the the row. I'm stuck at this point. Any help appreciated.
Demo: https://codesandbox.io/s/zq185w2zkm
import React, { useState } from "react";
import ReactDOM from "react-dom";
import { Table, Button, Input } from "reactstrap";
function App() {
const [rows, setRows] = useState([{}]);
const handleChange = index => e => {
const { name, value } = e.target;
const rows = [...rows];
rows[index] = {
[name]: value
};
setRows(rows);
};
const handleAddRow = () => {
const item = {
column_1: "",
column_2: ""
};
setRows([...rows, item]);
};
const handleRemoveRow = () => {
setRows(rows.slice(0, -1));
};
const handleRemoveSpecificRow = index => () => {
const rows = [...rows];
rows.slice(index, 1);
setRows(rows);
};
return (
<div>
<Table>
<thead className="thead-light">
<tr>
<th>#</th>
<th>Column 1</th>
<th>Column 2</th>
<th />
</tr>
</thead>
<tbody>
{rows.map((item, index) => (
<tr id="addr" key={index}>
<td>{index}</td>
<td>
<Input
type="text"
name="name"
value={rows[index].column_1}
onChange={handleChange(index)}
/>
</td>
<td>
<Input
type="text"
name="mobile"
value={rows[index].column_2}
onChange={handleChange(index)}
/>
</td>
<td>
<Button
outline
color="danger"
onClick={handleRemoveSpecificRow(index)}
>
Remove
</Button>
</td>
</tr>
))}
</tbody>
</Table>
<Button onClick={handleAddRow}>Add Row</Button>
<Button color="danger" onClick={handleRemoveRow}>
Delete Row
</Button>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
I too had my fair share of doubts like this, focus towards array/object manipulation techniques. Always manipulate data in a controlled way using unique id, key, etc..
https://codesandbox.io/s/y2lqj9qnjz
import React, { useState } from "react";
import ReactDOM from "react-dom";
import { Table, Button, Input } from "reactstrap";
function App() {
const [rows, setRows] = useState([]);
const handleChange = item => e => {
const { name, value } = e.target;
// const rows = [...rows];
// rows[index] = {
// [name]: value
// };
let items = rows.map(row => {
if (row.id === item.id) {
row[name] = value;
}
return row;
});
setRows(items);
};
const handleAddRow = () => {
let item = {
id: rows.length + 1,
column_1: "",
column_2: ""
};
setRows([...rows, item]);
};
const handleRemoveRow = () => {
setRows(rows.slice(0, -1));
};
const handleRemoveSpecificRow = item => () => {
// const rows = [...rows];
// rows.splice(index, 1);
// setRows(rows);
let items = rows.filter(row => row.id != item.id);
setRows(items);
};
console.log(rows);
return (
<div>
{rows.length != 0 && (
<Table>
<thead className="thead-light">
<tr>
<th>#</th>
<th>Column 1</th>
<th>Column 2</th>
<th />
</tr>
</thead>
<tbody>
{rows.map((item, index) => (
<tr id="addr" key={index}>
<td>{item.id}</td>
<td>
<Input
type="text"
name="column_1"
value={item.column_1}
onChange={handleChange(item)}
/>
</td>
<td>
<Input
type="text"
name="column_2"
value={item.column_2}
onChange={handleChange(item)}
/>
</td>
<td>
<Button
outline
color="danger"
onClick={handleRemoveSpecificRow(item)}
>
Remove
</Button>
</td>
</tr>
))}
</tbody>
</Table>
)}
<Button onClick={handleAddRow}>Add Row</Button>
<Button color="danger" onClick={handleRemoveRow}>
Delete Row
</Button>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
https://codesandbox.io/s/y2lqj9qnjz
I've updated the link above.
import React, { useState } from "react";
import ReactDOM from "react-dom";
import { Table, Button, Input } from "reactstrap";
function App() {
const [rows, setRows] = useState([
{
id: 1,
column_1: "",
column_2: ""
}
]);
const handleChange = (item) => (e) => {
const { name, value } = e.target;
// const rows = [...rows];
// rows[index] = {
// [name]: value
// };
let items = rows.map((row) => {
if (row.id === item.id) {
row[name] = value;
}
return row;
});
setRows(items);
};
const handleAddRow = () => {
let item = {
id: rows[rows.length - 1].id + 1,
column_1: "",
column_2: ""
};
setRows([...rows, item]);
};
const handleRemoveRow = () => {
setRows(rows.slice(0, -1));
};
const handleRemoveSpecificRow = (item) => () => {
// const rows = [...rows];
// rows.splice(index, 1);
// setRows(rows);
let items = rows.filter((row) => row.id != item.id);
setRows(items);
};
return (
<div>
{rows.length != 0 && (
<Table>
<thead className="thead-light">
<tr>
<th>#</th>
<th>Column 1</th>
<th>Column 2</th>
<th />
</tr>
</thead>
<tbody>
{rows.map((item, index) => (
<tr id="addr" key={index}>
<td>{item.id}</td>
<td>
<Input
type="text"
name="column_1"
value={item.column_1}
onChange={handleChange(item)}
/>
</td>
<td>
<Input
type="text"
name="column_2"
value={item.column_2}
onChange={handleChange(item)}
/>
</td>
<td>
<Button
outline
color="danger"
onClick={handleRemoveSpecificRow(item)}
>
Remove
</Button>
</td>
</tr>
))}
</tbody>
</Table>
)}
<Button onClick={handleAddRow}>Add Row</Button>
<Button color="danger" onClick={handleRemoveRow}>
Delete Row
</Button>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);