how to toggle through an array with the useState hook code example
Example 1: how to set value in array react hook usestate
const[array,setArray]= useState([
{id: 1, value: "a string", othervalue: ""},
{id: 2, value: "another string", othervalue: ""},
{id: 3, value: "a string", othervalue: ""},
])
const updateItem =(id, whichvalue, newvalue)=> {
var index = array.findIndex(x=> x.id === id);
let g = array[index]
g[whichvalue] = newvalue
if (index === -1){
// handle error
console.log('no match')
}
else
setArray([
...array.slice(0,index),
g,
...array.slice(index+1)
]
);
}
//how to use the function
onPress={()=>updateItem(2,'value','ewfwf')}
onPress={()=>updateItem(1,'othervalue','ewfwf')}
/*
the first input of the function is the id of the item
the second input of the function is the atrribute that you wish to change
the third input of the function is the new value for that attribute
It's a pleasure :0
~atlas
*/
Example 2: simple usestate example
// First: import useState. It's a named export from 'react'
// Or we could skip this step, and write React.useState
import React, { useState } from 'react';
import ReactDOM from 'react-dom';
// This component expects 2 props:
// text - the text to display
// maxLength - how many characters to show before "read more"
function LessText({ text, maxLength }) {
// Create a piece of state, and initialize it to `true`
// `hidden` will hold the current value of the state,
// and `setHidden` will let us change it
const [hidden, setHidden] = useState(true);
// If the text is short enough, just render it
if (text.length <= maxLength) {
return {text};
}
// Render the text (shortened or full-length) followed by
// a link to expand/collapse it.
// When a link is clicked, update the value of `hidden`,
// which will trigger a re-render
return (
{hidden ? `${text.substr(0, maxLength).trim()} ...` : text}
{hidden ? (
setHidden(false)}> read more
) : (
setHidden(true)}> read less
)}
);
}
ReactDOM.render(
,
document.querySelector('#root')
);