Suppose I have a component that takes in MeetingData as an object and populates a <p> element with specific items from that object:
import React from 'react';
export default function MeetingsCard({ meetingData }) {
return (
<div className="col-xl-1-12" style={{ margin: "10px", background: "#1A4565", border: "double" }}>
<div className="card" style={{ border: "none", width: "100%" }}>
<div className="card-body" style={{ width: "100%", background: "lightBlue" }}>
<h3 className="card-title" style={{ marginLeft: "10px" }}>Meetings</h3>
<p style={{ marginLeft: "50px" }}>Meeting location: {meetingData.meeting_location}, Meeting Date: {meetingData.meeting_date}</p>
<hr style={{ color: "grey" }} />
</div>
</div>
</div>
)
}
In this case, it expects there 2 be only a single item for meetingData.meeting_date and a single item for meetingData.meeting_location. But suppose the returned object has more than one and I need to populate multiple <p> elements? How would I do that if the meeting object/array looks like this:
meetingData = [
{
"date_time": "2021-07-07",
"meeting_location": "test-location1",
"name": "John Doe"
},
{
"date_time": "2021-07-08",
"meeting_location": "test-location2",
"name": "John Doe"
}
]
Just loop your data and add each entry as their own. Also good idea to create own component for the meeting entries so that it's easier to customize it if necessary.
MeetingEntry:
import React from 'react';
export default function MeetingEntry({ meetingData }) {
return (
<p style={{ marginLeft: "50px" }}>Meeting location: {meetingData.meeting_location}, Meeting Date: {meetingData.meeting_date}</p>
)
}
MeetingsCard:
import React from 'react';
import MeetingEntry from './MeetingEntry';
export default function MeetingsCard({ data }) {
return (
<div className="col-xl-1-12" style={{ margin: "10px", background: "#1A4565", border: "double" }}>
<div className="card" style={{ border: "none", width: "100%" }}>
<div className="card-body" style={{ width: "100%", background: "lightBlue" }}>
<h3 className="card-title" style={{ marginLeft: "10px" }}>Meetings</h3>
{data.map((el, idx) => (
<MeetingEntry notification={el} key={idx} />
))}
<hr style={{ color: "grey" }} />
</div>
</div>
</div>
)
}
You can just loop through the array and display data something like below
export default function MeetingsCard({ meetingData }) {
return (
<div className="col-xl-1-12" style={{ margin: "10px", background: "#1A4565", border: "double" }}>
<div className="card" style={{ border: "none", width: "100%" }}>
<div className="card-body" style={{ width: "100%", background: "lightBlue" }}>
<h3 className="card-title" style={{ marginLeft: "10px" }}>Meetings</h3>
{meetingData.map(meeting => (
<p style={{ marginLeft: "50px" }}>Meeting location: {meeting.meeting_location}, Meeting Date: {meeting.date_time}</p>))
<hr style={{ color: "grey" }} />
</div>
</div>
</div>
)
}
Related
import React, { useEffect, useState } from "react";
import axios from "axios"
import '../App.css';
import ProgressBarForCO from "../progress bar/ProgressBarForCO"
import ProgressBarForNO from "../progr`your text`ess bar/ProgressBarForNO";
import ProgressBarForNO2 from "../progress bar/ProgressBarForNO2";
import ProgressBarForSO2 from "../progress bar/ProgressBarForSO2";
export default function Home() {
const [airData, setAirData] = useState([]);
useEffect(
() => {
loadAirData();
}, []
);
const loadAirData = async () => {
const result = await axios.get("http://localhost:8080/AirData");
setAirData(result.data);
}
return (
<div >
<div className='container'>
<div className='py-4'>
{
airData.map((data) => (
<h1 style={{
color: 'white',
fontSize: '30px'
}}>
Data Received Time : {data.timeStamp}
</h1>
))}
</div>
<div className="containerBox" style={{ marginTop: '25px' }}>
{
airData.map((data) => (
<>
<div class="card">
<div class="container">
<p style={{ color: 'black' }}>Carbon Monoxide </p>
<div style={{
width: '100px',
display: 'block',
marginLeft: 'auto',
marginRight: 'auto'
}}>
<ProgressBarForCO score={data.co} /></div>
</div>
</div>
</>
))}
{
airData.map((data) => (
<>
<div class="card">
<div class="container">
<p style={{ color: 'black' }}>Nitric oxide </p>
<div style={{
width: '100px',
display: 'block',
marginLeft: 'auto',
marginRight: 'auto'
}}>
<ProgressBarForNO score={data.no} /></div>
</div>
</div>
</>
))}
</div>
<br />
<br />
<div className="containerBox">
{
airData.map((data) => (
<>
<div class="card">
<div class="container">
<p style={{ color: 'black' }}>Nitrogen dioxide</p>
<div style={{
width: '100px',
display: 'block',
marginLeft: 'auto',
marginRight: 'auto'
}}>
<ProgressBarForNO2 score={data.no2} /></div>
</div>
</div>
</>
))}
{
airData.map((data) => (
<>
<div class="card">
<div class="container">
<p style={{ color: 'black' }}>Sulphur dioxide </p>
<div style={{
width: '100px',
display: 'block',
marginLeft: 'auto',
marginRight: 'auto'
}}>
<ProgressBarForSO2 score={data.so2} /></div>
</div>
</div>
</>
))}
</div>
<ul className="final">
<li style={{ color: '#66FF00' }}>Excellent</li>
<li style={{ color: '#90EE90' }}>Good</li>
<li style={{ color: 'yellow' }}>Lightly polluted</li>
<li style={{ color: '#FFBF00' }}>Heavily polluted</li>
<li style={{ color: 'red' }}>Severely polluted</li>
</ul>
</div>
</div>
)
}
I tried setting the "setAirData(result.data[0]". But it is displaying an error.
You are mapping your airData in the component render, therefore, it has to be an array. When you set it to be results.data[0], airData is converted to an object and it cannot be mapped.
You can do setAirData([results.data[0]]) instead and it will set the value to be an array with only the first element, and it will render just fine.
the compiler is complaining that airData.map is not a function. that means that airData is not an array :
const result = await axios.get("http://localhost:8080/AirData");
console.log(result.data) // <-- add this line
setAirData(result.data);
Most probably here that your endpoint is returning un object as result.data not an array
the airdata is not an array.
setAirData([results.data[0]])
suppose i have a div element
<div
style={{
borderTopLeftRadius: "10px",
borderTopRightRadius: "10px",
background: "#edf2f8",
border: "1px solid #edf2f8",
borderBottom: "0px",
width:"300px",
marginLeft:"20px",
backgroundPosition: "center",
}}
>
hello world
</div>
I want to use the onclick function to hide/show state of the div . For example when a user clicks in the div I hide it .. How can I achieve that in react ?
Store a display value in component state and toggle it via the onClick handler. Conditionally render the entire div.
Example:
function App() {
const [display, setDisplay] = React.useState(true);
return (
<div className="App">
{display && (
<div
onClick={() => setDisplay(false)}
style={{
borderTopLeftRadius: "10px",
borderTopRightRadius: "10px",
background: "#edf2f8",
border: "1px solid #edf2f8",
borderBottom: "0px",
width: "300px",
marginLeft: "20px",
backgroundPosition: "center"
}}
>
hello world
</div>
)}
<button type="button" onClick={() => setDisplay(true)}>
Reply
</button>
</div>
);
}
This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 1 year ago.
my React code doesn't works.
I've an array, and, for each item, I need to render a card.
But it doesn't works.
This is all the code:
const Home: NextPage = () => {
const [servers, setServers] = useState({});
async function getServers() {
console.log('ready');
const response = await fetch('http://localhost:3000/server/servers').then(
(res) => res.json()
);
setServers(response);
console.log(response);
console.log('servers object updated: ' + JSON.stringify(servers));
}
useEffect(() => {
getServers();
import('bootstrap/dist/js/bootstrap');
WebFont.load({
google: {
families: ['Karla:600', 'sans-serif'],
},
});
}, []);
useEffect(() => {
console.log('servers object updated: ' + JSON.stringify(servers));
}, [servers]);
return (
<div className="app">
<div className="container">
<div className="row" style={{ color: 'white' }}>
{servers.database?.map((server, index) => (
<div key={index} className="col">
<div
className="card"
style={{
width: '18rem',
backgroundColor: '#101114',
color: 'white',
marginTop: '80px',
borderRadius: '15px',
boxShadow: '4px 3px 5px 0px #7335fb',
}}
>
<img
src="https://cdn.discordapp.com/icons/843104500713127946/a_91371d39bec9e454d0f4ccacbfaea9f8.gif?size=512"
className="card-img-top"
alt="Icona server"
style={{
borderRadius: '50%',
width: '96px',
marginLeft: '20px',
marginTop: '60px',
}}
/>
<div className="card-body">
<h5 className="card-title">
{servers.bot[index].name || 'Errore!'}
</h5>
<br />
<p className="card-text">{server.shortDescription}</p>
<br />
<a
href="#"
className="btn"
style={{ backgroundColor: '#5316d9', color: 'white' }}
>
Entra
</a>
<a
href="#"
className="btn"
style={{
marginLeft: '10px',
backgroundColor: '#5316d9',
color: 'white',
}}
>
Visita
</a>
<br />
</div>
</div>
</div>
))}
</div>
</div>
</div>
);
};
export default Home;
The problem is here:
servers.database?.map((server, index) => (
<div key={index} className="col">
<div
className="card"
style={{
width: '18rem',
backgroundColor: '#101114',
color: 'white',
marginTop: '80px',
borderRadius: '15px',
boxShadow: '4px 3px 5px 0px #7335fb',
}}
>
<img
src="https://cdn.discordapp.com/icons/843104500713127946/a_91371d39bec9e454d0f4ccacbfaea9f8.gif?size=512"
className="card-img-top"
alt="Icona server"
style={{
borderRadius: '50%',
width: '96px',
marginLeft: '20px',
marginTop: '60px',
}}
/>
<div className="card-body">
<h5 className="card-title">{servers.bot[index].name || 'Errore!'}</h5>
<br />
<p className="card-text">{server.shortDescription}</p>
<br />
<a
href="#"
className="btn"
style={{ backgroundColor: '#5316d9', color: 'white' }}
>
Entra
</a>
<a
href="#"
className="btn"
style={{
marginLeft: '10px',
backgroundColor: '#5316d9',
color: 'white',
}}
>
Visita
</a>
<br />
</div>
</div>
</div>
));
Here the console output:
Someone know why it doesn't works?
No error, all works fine, but he doesn't load array.
VScode tell me that the initial useState value doesn't contain necessary data, but it arrive from database after, so I don't care.
If you have any suggestion/solution, please tell me.
Thanks in advance and sorry for bad English!
If you check your console.log("servers object updated: " + JSON.stringify(servers)); log you'll see that it's an object without a database property.
From what I can see of the logged state, the render should use the servers.servers property array to map:
{servers.servers?.map((server, index) => (
<div key={index} className="col">
<div className="card" style={{ width: "18rem", backgroundColor: "#101114", color: "white", marginTop: "80px", borderRadius: "15px", boxShadow: "4px 3px 5px 0px #7335fb" }}>
<img src="https://cdn.discordapp.com/icons/843104500713127946/a_91371d39bec9e454d0f4ccacbfaea9f8.gif?size=512" className="card-img-top" alt="Icona server" style={{ borderRadius: "50%", width: "96px", marginLeft: "20px", marginTop: "60px" }} />
<div className="card-body">
<h5 className="card-title">{servers.bot[index].name || "Errore!"}</h5><br />
<p className="card-text">{server.shortDescription}</p><br />
<a href="#" className="btn" style={{ backgroundColor: "#5316d9", color: "white" }}>Entra</a>
<a href="#" className="btn" style={{ marginLeft: "10px", backgroundColor: "#5316d9", color: "white" }}>Visita</a>
<br />
</div>
</div>
</div>
))}
I have a layout file where I made footer and navigation and I insert these two functions in Layout const (code below). In the new file, I just need the Navigation function so how I can insert it without a footer? Because when I write in my new file import Navigation from "../components/layout" and the in code insert I've got error...
const Layout = ({ children }) => {return (
<div>
<Navigation></Navigation>
<Global
styles={{
html: {
backgroundColor: "#fff",
color: "#111",
fontFamily: `'Poppins', sans-serif`,
fontSize: 14,
[Screen.S]: {
fontSize: 16,
},
[Screen.M]: {
fontSize: 18,
},
[Screen.L]: {
fontSize: 20,
},
},
a: {
color: "unset",
},
}}
/>
{children}
<Footer></Footer>
</div>
)
}
function Navigation() { const [navbarOpen, setNavbarOpen] = useState(false) return (
<header
css={{
width: "100%",
maxWidth: "100%",
padding: "0 24px",
position: "fixed",
background: "#fff",
boxShadow: "0 0 0.35rem rgba(0,0,0,.25)",
zIndex: "100",
top: 0,
}}
>
<div
css={{
gridAutoFlow: "column",
minHeight: "4.5rem",
display: "grid",
maxWidth: 1200,
margin: "0 auto",
gridTemplateColumns: "auto 1fr",
alignItems: "center",
paddingLeft: 35,
}}>
<Link to="/ ">
<img style={{ height: "2.5rem" }} src={logo}/>
</Link>
<Toggle
navbarOpen={navbarOpen}
onClick={() => setNavbarOpen(!navbarOpen)}
>
{navbarOpen ? <Hamburger open /> : <Hamburger />}
</Toggle>
{navbarOpen ? (
<NavBoxIcons>
<NavbarSocialLinks />
</NavBoxIcons>
) : (
<NavBox open>
<div>
<HeaderLink>About</HeaderLink>
<HeaderLink>Blog</HeaderLink>
</div>
<div>
<NavbarLinks />
</div>
</NavBox>
)
}
</div>
</header >
)
}
function Footer() { return (
<footer
css={{
padding: "6rem 2rem",
fontSize: "1rem",
minHeight: 160,
fontFamily: "sans-serif",
...Css.container,
}}
>
<div
css={{
display: "flex",
flexDirection: "column",
marginBottom: "3.6rem",
}}
>
<div
css={{
fontSize: "1.2rem",
display: "grid",
gridGap: "0.8rem",
}}>
<a>
<span>Privacy police</span>
</a>
</div>
</div>
<div
css={{
display: "grid",
gridTemplateColumns: "1fr auto",
alignItems: "center",
fontWeight: "lighter",
}}>
<div css={{ display: "flex", flexDirection: "column" }}>
<span>My Page</span>
</div>
</div>
</footer>
)
}
try exporting both Navigation and Footer like this
//at bottom of file
export {Navigation, Footer}
import individual component like this
import {Navigation} from 'components/layout'
or
import {Navigation,Footer} from 'components/layout'
lookup exporting in js
I have a form to add clients to a database and the results are shown at the end of the page; the list is displayed using componentDidMount(). I also have a separate form to manage employees. In this form I add the employees to the other database but the results are being displayed on the same fields as the clients table, and when this happens, the clients information gets hidden.
I am putting them in two different places, so I don't understand why is this happening. I also wanted to mention that the employees form is being imported from another component. Here is some of my code:
render() {
const employees = this.state.employees;
const employeesList = employees.length ? (
employees.map(employee => {
return (
<div key={employee.id}>
<div className="employee-list">
<table style={{ width: "60%", tableLayout: "fixed", border: "1px", background: "grey" }}>
<React.Fragment>
<tr>
<td style={{ width: "50px", textAlign: "center" }}>{employee.id}</td>
<td style={{ width: "100px", textAlign: "center" }}>{employee.firstName}</td>
<td style={{ width: "100px", textAlign: "center" }}>{employee.lastName}</td>
<td style={{ width: "100px", textAlign: "center" }}>{employee.email}</td>
<td><Link style={{ width: "70px", border: "1px solid white" }} className="btn btn-info" to={'/auth/employees/' + employee.id}>Edit
</Link>
<button style={{ background: "red", color: "white", width: "70px" }} className="btn btn-warning" onClick={(e) => { if (window.confirm(`Are you sure you wish to delete ${employee.firstName} ${employee.lastName} permanently?`)) this.handleDeleteEmployee(employee.id) }}>
Delete
</button>
</td>
</tr>
</React.Fragment>
</table>
</div>
</div>
)
})
) : (
<div >No Employees in database</div>
);
const clients = this.state.clients;
const clientsList = clients.length ? (
clients.map(client => {
return (
<div key={client.id}>
<div className="card-content">
<table style={{ width: "100%", tableLayout: "fixed", border: "1px", background: "white" }}>
<tbody>
<tr>
<td style={{ width: "50px", textAlign: "center" }}>{client.id}</td>
<td style={{ width: "100px", textAlign: "center" }}>{client.lastName}</td>
<td style={{ width: "100px", textAlign: "center" }}>{client.firstName}</td>
<td style={{ width: "100px", textAlign: "center" }}>{client.phone}</td>
<td style={{ width: "160px", textAlign: "center" }}>{client.petName}</td>
<td style={{ width: "120px", textAlign: "center" }}>{client.breed}</td>
<td style={{ width: "367px", textAlign: "center" }}>{client.notes}</td>
<td><Link style={{ width: "70px", border: "1px solid white" }} className="btn btn-info" to={'api/clients/' + client.id}>Edit
</Link>
<button style={{ background: "red", color: "white", width: "70px" }} className="btn btn-warning" onClick={(e) => { if (window.confirm(`Are you sure you wish to delete ${client.firstName} ${client.lastName} permanently?`)) this.handleDeleteClient(client.id) }}>
Delete
</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
)
})
) : (
<div >No clients in database</div>
);
return (
<div className="container">
<div className="row">
<div className="col-md-12">
<hr style={{ background: "white" }}></hr>
<h1 style={{ textAlign: 'center' }}><b>Welcome to the Admin Panel Paola</b></h1>
<Button color="warning" style={{ fontSize: "20px", color: "navy", border: "solid 1px navy", marginBottom: "15px" }} onClick={this.handleLogOut}>Logout</Button>
<Button style={{ fontSize: "20px", background: "navy", marginLeft: "15px", marginBottom: "15px" }} onClick={this.toggleEmployeeFormFunction}>Add new Staff members (click to hide/show)</Button>
{
this.state.toggleEmployeeForm ? (
<div><EmployeeSignupForm>
</EmployeeSignupForm>
{employeesList}
</div>
) : (
null
)
}
<div className="col-md-8 bg-dark" style={{ border: '1px solid white', color: 'white', marginBottom: "30px" }}>
<form className="white" onSubmit={this.handleFormSubmit.bind(this)} style={{ marginBottom: "50px" }}>
<h2 className="grey-text text-darken-3" style={{ textAlign: "center", marginTop: "15px" }}>Add a New Client</h2>
<p>* Fields required</p>
<hr style={{ background: "white" }}></hr>
<div className="input-field">
<label htmlFor="lastName">* Last Name</label>
<input type="text" id='lastName' value={this.state.lastName} onChange={this.handleChange} />
</div>
<div className="input-field">
<label htmlFor="firstName">* First Name</label>
<input type="text" id='firstName' value={this.state.firstName} onChange={this.handleChange} />
</div>
<div className="input-field">
<label htmlFor="phone">* Phone</label>
<input type="text" id='phone' value={this.state.phone} onChange={this.handleChange} />
</div>
<div className="input-field">
<label htmlFor="petName">* Pet Name</label>
<input type="text" id='petName' value={this.state.petName} onChange={this.handleChange} />
</div>
<div className="input-field">
<label htmlFor="breed">* Breed</label>
<input type="text" id='breed' value={this.state.breed} onChange={this.handleChange} />
</div>
<div className="input-field">
<label htmlFor="notes">Notes</label>
<input type="text" id='notes' value={this.state.notes} onChange={this.handleChange} />
</div>
<div className="input-field">
<button className="btn-primary lighten-1 z-depth-0" onClick={this.handleFormSubmit}
>Add Client</button>
</div>
</form>
</div>
<div className="row">
<div className="col-md-12">
<div style={{ background: "white", paddingTop: "12px", marginBottom: "100px" }}>
<h6><b>
<h1 style={{ textAlign: "center" }}>Clients List</h1>
<span style={{ border: "1px solid", padding: "8px 17px 8px 17px" }}>Id</span>
<span style={{ border: "1px solid", padding: "8px 11px 8px 12px" }}>Last Name</span>
<span style={{ border: "1px solid", padding: "8px 8px 8px 8px" }}> First Name</span>
<span style={{ border: "1px solid", padding: "8px 27px 8px 25px" }}>Phone</span>
<span style={{ border: "1px solid", padding: "8px 44px 8px 44px" }}>Pet Name</span>
<span style={{ border: "1px solid", padding: "8px 37px 8px 38px" }}>Breed</span>
<span style={{ border: "1px solid", padding: "8px 200px 8px 200px", background: "white" }}>Notes / Actions</span>
</b></h6>
{clientsList}
</div>
</div>
</div>
</div>
</div >
)
}
Thanks in advance