usestate hook list of objects code example
Example 1: usestate nested object
const [currentApp, setCurrentApp] = useState({
userID: null,
hospitalName: null,
hospitalID: null,
date: null,
time: null,
timestamp: null,
slots: 1,
appointmentType: null
})
const [appointmentType, setAppointmentType] = useState({
Granulocytes: {
bloodType:null,
message: null
}
})
const handleGranChange = (e) => {
setAppointmentType({...appointmentType, Granulocytes : {
...appointmentType.Granulocytes,
[e.target.id] : e.target.value}
})
setCurrentApp({ ...currentApp, ['appointmentType'] : appointmentType })
console.log(currentApp)
}
Example 2: simple usestate example
import React, { useState } from 'react';
import ReactDOM from 'react-dom';
function LessText({ text, maxLength }) {
const [hidden, setHidden] = useState(true);
if (text.length <= maxLength) {
return <span>{text}</span>;
}
return (
<span>
{hidden ? `${text.substr(0, maxLength).trim()} ...` : text}
{hidden ? (
<a onClick={() => setHidden(false)}> read more</a>
) : (
<a onClick={() => setHidden(true)}> read less</a>
)}
</span>
);
}
ReactDOM.render(
<LessText
text={`Focused, hard work is the real key
to success. Keep your eyes on the goal,
and just keep taking the next step
towards completing it.`}
maxLength={35}
/>,
document.querySelector('#root')
);