Do you know why am I not a able to map through the todos? I am following tutorial online and I have it exactly the same as the other guy but It's not mapping through the data. I get the json back and I can see the todos inside of the client-side console.
import React, { Fragment, useEffect, useState } from "react";
const ListTodos = () => {
const [todos, setTodos] = useState([]);
const getTodos = async () => {
try {
const response = await fetch("http://localhost:5000/todos");
const jsonData = await response.json();
setTodos(jsonData);
} catch (err) {
console.error(err.message);
}
};
useEffect(() => {
getTodos();
}, []);
return (
<Fragment>
<table className="table mt-5 text-center">
<thead>
<tr>
<th>Description</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
{todos.map((todo) => {
<tr>
<td>{todo.description}</td>
<td>Edit</td>
<td>Delete</td>
</tr>;
})}
</tbody>
</table>
</Fragment>
);
};
Thanks
You should return the JSX if you are using curly braces in function. Like This
{todos.map((todo) => {
return (<tr>
<td>{todo.description}</td>
<td>Edit</td>
<td>Delete</td>
</tr>;
)})}
Else use parentheses to directly return , Like This
{todos.map((todo) => (<tr>
<td>{todo.description}</td>
<td>Edit</td>
<td>Delete</td>
</tr>
))}
you should use round brackets insted of curly braces in the map function
return (
<Fragment>
<table className="table mt-5 text-center">
<thead>
<tr>
<th>Description</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
{todos.map((todo) => (
<tr>
<td>{todo.description}</td>
<td>Edit</td>
<td>Delete</td>
</tr>
))}
</tbody>
</table>
</Fragment>
);
Related
I have a table using normal HTML in reactjs:
const [user, setUser] = useState(null);
useEffect(() => {
axios
.get("http://localhost:8080/api/users")
.then((response) => {
setUser(response.data);
});
}, [url]);
const [rowIndex, setRowIndex] = useState("");
if (user) {
return (
<div>
<table className="table">
<thead>
<tr>
<th scope="col">Name</th>
<th scope="col">Age</th>
<th scope="col">Department</th>
<th scope="col">Action</th>
</tr>
</thead>
<tbody>
{user.map((item) => (
<tr>
<td>{item.name}</td>
<td>{item.age}</td>
<td>{item.department}</td>
<td><button>Click</button></td>
</tr>
))}
</tbody>
</table>
</div>
);
}
If in Javascript, I can simply set <tr onclick="getIndex(this)"> and calling function getIndex(x) {console.log(x.rowIndex)} to get the row number.
But it's not working in ReactJS. How can I get the rowIndex in ReactJS?
Use index inside your map method and then use this variable inside your button's onClick method
const [user, setUser] = useState(null);
useEffect(() => {
axios
.get("http://localhost:8080/api/users")
.then((response) => {
setUser(response.data);
});
}, [url]);
const [rowIndex, setRowIndex] = useState("");
if (user) {
return (
<div>
<table className="table">
<thead>
<tr>
<th scope="col">Name</th>
<th scope="col">Age</th>
<th scope="col">Department</th>
<th scope="col">Action</th>
</tr>
</thead>
<tbody>
{user.map((item, index) => (
<tr>
<td>{item.name}</td>
<td>{item.age}</td>
<td>{item.department}</td>
<td><button onclick={() => setRowIndex(index)}>Click</button></td>
</tr>
))}
</tbody>
</table>
</div>
);
}
I have passed an array of objects in useState hook as the initial state and i want to iterate over it using map method in other component, i have passed the current state as prop in the other object and have used map method over it but console message still shows values.map is not a function, i know we can only use map method on array i have done that only still the error shows.
created state and passed an array of objects-
const [values, setValues] = useState([
{
name: "Vansh",
age: 22,
email: "vansh#gmail.com",
},
]);
Passed values as props in Home component-
<Home
addFormData={addFormData}
setAddFormData={setAddFormData}
values={values}
setValues={setValues}
/>
Code of my home component-
const Home = ({ values }) => { return (
<div>
<table>
<thead>
<tr>
<th>name</th>
<th>age</th>
<th>email</th>
</tr>
</thead>
<tbody>
{values.map((val, index) => (
<tr>
<td key={val.index}>{val.name}</td>
<td key={val.index}>{val.age}</td>
<td key={val.index}>{val.email}</td>
</tr>
))}
</tbody>
</table>
<Link to="/form">
<button>FORM</button>
</Link>
</div> ); };
Please see the code it's working fine export below your missing export.
const Home = ({ values }) => {
// console.log(values);
return (
<div>
<table>
<thead>
<tr>
<th>name</th>
<th>age</th>
<th>email</th>
</tr>
</thead>
<tbody>
{values.map((val, index) => (
<tr>
<td key={val.index}>{val.name}</td>
<td key={val.index}>{val.age}</td>
<td key={val.index}>{val.email}</td>
</tr>
))}
</tbody>
</table>
</div>
);
};
export default Home;
Please see the code SandBoxLink
import React,{useState,useEffect} from 'react';
import "../Track.css";
const Tracker = () => {
const[data,setData]= useState([]);
const getCovidData = async() =>{
const res = await fetch('https://api.rootnet.in/covid19-in/stats/latest');
const actualData = await res.json();
console.log(actualData.regional);
setData(actualData.regional);
}
useEffect(() => {
getCovidData();
}, []);
return (
<>
<div className="conatiner-fluid mt-5">
<div className="main-heading">
<h1 className="mb-5 text-center"> <span className="font-weight-bold">INDIA</span> COVID-19 DASHBOARD</h1>
</div>
<div className="table-responsive">
<table className="table table-hover">
<thead className="thead-dark">
<tr>
<th> STATE</th>
<th> CONFIRMED</th>
<th> RECOVERED</th>
<th> DEATHS</th>
<th> ACTIVE</th>
<th> UPDATED</th>
</tr>
</thead>
<tbody>
{
data && data.map((curElem,ind,regional) => {
return(
<tr key={ind}>
<th> {curElem?.loc} </th>
<td> {curElem?.confirmedCasesIndian} </td>
<td> {curElem?.discharged} </td>
<td> {curElem?.deaths} </td>
<td> {curElem?.lastOriginUpdate} </td>
</tr>
)
})
}
</tbody>
</table>
</div>
</div>
</>
)
}
export default Tracker
I am not getting output of api values in the output page. Pls help as their may be the mistake in map function. pls share your views and and share solution if possible.
regional is inside data object.
{
"success": true,
"data": {
"summary": {...}
"unofficial-summary" : [...],
"regional" : [...]
...
}
}
You need to change setData(actualData.regional); as below
// ...
const getCovidData = async() =>{
const res = await fetch('https://api.rootnet.in/covid19-in/stats/latest');
const actualData = await res.json();
console.log(actualData.regional);
setData(actualData.data.regional);
}
I am successfully returning data from my axios call on page load.
constructor(props) {
super(props);
this.state = {
myData: []
}
}
componentDidMount() {
let context= this;
axios.get('http://localhost:3000/returntestvalues',{
})
.then((res) => {
console.log("Res os: ", res.data)
context.setState({
myData: res.data
});
})
console.log("res.data", this.state.myData)
}
As you can see there, I am setting the State to the returned data. Now, I want to output this into a table:
render() {
return (
<body onload="renderData()">
<table id="customers">
<tr>
<th>Name</th>
<th>Email</th>
<th>Message</th>
</tr>
<tr>
{this.state.myData?.length > 0
? this.state.myData.map((data, index) => (
<tr key={index}>
<td>{data.name}</td>
<td>{data.email}</td>
<td>{data.message}</td>
</tr>
))
: "No Data Found"}
</tr>
</table>
</body>
);
}
}
however, I don't know how to do this through react, I've only ever done it through ejs. Can anyone help?
render() {
return (
<body onload="renderData()">
<table id="customers">
<tr>
<th>Name</th>
<th>Email</th>
<th>Message</th>
</tr>
<tr>
{this.state.myData?.length > 0
? this.state.myData.map((data, index) => (
<React.Fragment key={index}>
<td>{data.name}</td>
<td>{data.email}</td>
<td>{data.message}</td>
</React.Fragment>
))
: "No Data Found"}
</tr>
</table>
</body>
);
}
}
Here i am assuming that the keys are name email and message. you can change yours.
You can map your received data like below.
return (
<body onload="renderData()">
<table id="customers">
<tr>
<th>Name</th>
<th>Email</th>
<th>Message</th>
</tr>
{this.state.myData?.length>0 && this.state.myData.map(function(data,index){
return (<tr>
<td>{data.name}</td>
<td>{data.email}</td>
<td>{data.message}</td>
</tr>);
})}
</table>
</body>
);
I need to pass params from child component to the node elements from parent props.
Page component
export default function Categories() { const dispatch = useDispatch();
useEffect(() => {
dispatch(loaderAction(false));
return () => dispatch(loaderAction(true)); }, [dispatch]);
function handleClick(params) {
alert(); }
function handleEditClick(params) {
alert(); }
return (
<div className="categories-body">
<div className="categories-header">
<div className="left">
<h2>{t('[categories]')}</h2>
</div>
<div className="right">
<button className="button orange">{t('[addNewCategory]')}</button>
<LanguageSettings name="categoriesLanguageSetting" />
</div>
</div>
// Table component imported
<Table
action={
<>
//node elements
<button onClick={handleClick}>save</button>
<button onClick={handleEditClick}>edit</button>
</>
}
/>
</div> ); }
TableComponent
export default function Table({action}) {
return (
<table>
<thead>
<tr>
<th>Name</th>
<th>date</th>
<th>key</th>
<th>category</th>
<th>actions</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>1</td>
<td>1</td>
<td>1</td>
<td>{action}</td> //pass parameter to node props
</tr>
</tbody>
</table>
);
}
I have pass two buttons to the Table component and need to pass for example row id to button onClick
Just pass the function... not the component
const handleClick = id => alert();
<Table action={handleClick} />
function Table({action}) {
return (
<table>
...
<td><button onClick={() => action(`someId`)}>action</button></td>
</table>
);
}
Or if you insist, pass a function component not an element:
actions={({id}) => <button onClick={() => handleClick(id)}>save</button>}
// Usage
function Table({action}) {
const Action = props.action;
return (
<table>
...
<td><Action id="Some id"/></td>
</table>
);
}
in your page component, just pass the actions prop as a render prop function
function handleClick(params) {
console.log(params);
alert();
}
function handleEditClick(params) {
console.log(params);
alert();
}
return (
<Table
action={ (params) => (
<>
<button onClick={() => handleClick(params)}>save</button>
<button onClick={() => handleEditClick(params)}>edit</button>
</>
)
}
/>
)
and in the table component call that function with the desired params,
with this approach, you can extend the render prop function to deliver multiple params
function Table({action}) {
return (
<table>
<thead>
<tr>
<th>Name</th>
<th>date</th>
<th>key</th>
<th>category</th>
<th>actions</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>1</td>
<td>1</td>
<td>1</td>
<td>{action(23)}</td> // pass params here
</tr>
</tbody>
</table>
);
}