I want to have an edit mode to each field in a div that is mapped out from an array that I fetch from firbase. I succeeded doing that by conditioning the rendered field to the value of a boolean (editField) which I then manipulate using useState, like so:
in the functions seen up there I can manipulate the value of editTitle, so as to switch between the two functions by double clicking or clicking a button, and also update the field value in Firebase. as such:
this all works fine. HOWEVER,
if there are more that one divs rendered from the tasks[], then thay are obviously all effected to the flipping of editTitle's value from false to true, and by double clicking one field, all fields of same name in all divs swithc to edit mode. as such:
what can I do to target only the field in the task I want to edit? I've tried using the elemnt.id and index in some way bat can't seem to come up with the correct method...
const ifEditTitleIsTrue = (element, index) => {
return (
<div>
<input
type="text"
defaultValue={element.Title}
onChange={(e) => setUpdatedTitle(e.target.value)}
/>
<button className="exit__editmode-btn btn" onClick={exitEditMode}>
X
</button>
<button
className="update__edit-btn btn"
id="updateTitle"
onClick={(e) => updateField(e, element.id)}
>
ok
</button>
</div>
);
};
// if editTitle = false (default):
const ifEditTitleIsFalse = (element, index) => {
return (
<h3
id={index}
className="task-title"
onDoubleClick={() => setEditTitle(true)}
>
{element.Title}
</h3>
);
};
// edit mode for inCharge field
const ifEditInChargeIsTrue = (element, index) => {
return (
<div>
{
<GetCollaboratorsForEditMode
catchValueInCharge={catchValueInCharge}
/>
}
<button className="exit__editmode-btn btn" onClick={exitEditMode}>
X
</button>
<button
className="update__edit-btn btn"
id="updateInCharge"
onClick={(e) => updateField(e, element.id)}
>
ok
</button>
</div>
);
};
{tasks[0] &&
tasks.map((element, index) => (
<div id={element.id} className="task" key={element.id}>
{editTitle
? ifEditTitleIsTrue(element, index)
: ifEditTitleIsFalse(element, index)}
You need to keep track of what element is in edit mode. You can do it by storing the element id in your editTitle state, instead of just a boolean
const ifEditTitleIsFalse = (element, index) => {
...
onDoubleClick={() => setEditTitle(element.id)}
...
};
The condition to render an element in edit mode or view mode would change to:
{editTitle === element.id
? ifEditTitleIsTrue(element, index)
: ifEditTitleIsFalse(element, index)}
I've solved it!!!
insted of EditTitle being a boolean, it's just an empty string.
then the condition is editTitle === index ? some function : some othe function;
and the doubleclick is (()=> setEditTitle(index)).
So I'm trying to set up a mui-autocomplete component with additional buttons (Clear all (clear all values and close dropdown) + Apply (set value and close dropdown)) using ListboxComponent.
Issues:
when selecting options from the bottom of the list, the scroll position is reset to the top
cannot close the dropdown programmatically
Here is the ListboxComponent
ListboxComponent={(listBoxProps) => {
return (
<div>
<ul {...listBoxProps} />
<div>
<button
onMouseDown={(event) => {
// Disable blur
event.preventDefault();
}}
onClick={() => {
// clear values
setSelected([]);
}}
>
Clear All
</button>
<button
onMouseDown={(event) => {
// Disable blur
event.preventDefault();
}}
onClick={() => {
// apply value
}}
>
Apply
</button>
</div>
</div>
);
The options are rendered as follows:
renderOption={(optionProps, option, optionState) => {
return (
<li {...optionProps}>
<Checkbox
icon={icon}
checkedIcon={checkedIcon}
checked={optionState.selected}
/>
{option}
</li>
);
}}
So I'm using state to keep track of saving the selected values:
const [selectedResult, setSelected] = useState([]);
And when the option is selected - the state is updated
onChange={(event, selectedOptions) => {
setSelected(selectedOptions);
}}
But when the state changes, the component is re-rendered and the scroll is reset. It also seems that I can't use local variables to store the intermediate result, as the state won't update and the checkbox won't update.
StackBlitz link
Is there anything I can do to achieve this?
I'm trying to make a CRUD person function where each person has an array of skills.
I want a function where you're able to add/edit/remove skills on a given person.
Each array consist of a skill element as a string and a star element as an integer. I've made some dynamic inputfields with an add and a remove function for more/less inputfields in a bootstrap modal.
The data is fetched from Firebase with a useEffect and set as setData in EditPerson.jsx. No problem here.
The issue consist of 3 components atm: EditPerson -> ModalEditSkills -> EditSkills. (Please let me know if this is a bad structure).
I'm now able to set the useState of newData in SkillEdit.jsx with the correct data. This makes sure that on EditPerson I'll be able to view the correct data input from given in the EditSkills. Also if I console.log the data in EditSkills I can see that it works like a charm. But when I close the bootstrap modal and open it again the useState in index 0 have been reset to init useState (0).
I can't add images in the text here yet, so here's some links for the images if needed.
The image explains that the console.log tells me that the useState is set correct, but it stills reset the state of index 0 everytime I re-open the modal.
Hope that makes sense otherwise let me know.
ReactStars-choosen
Console.log
EditPerson.jsx
const EditPerson = () => {
const [data, setData] = useState({});
const [skills, setSkills] = useState([]);
const { id } = useParams();
useEffect(() => {
if (id) {
const fetchData = async () => {
const docRef = doc(db, "person", id);
try {
const docSnap = await getDoc(docRef);
setData(docSnap.data());
} catch (error) {
console.log(error);
}
};
fetchData().catch(console.error);
} else {
setData("");
}
}, [id]);
useEffect(() => {
if (data) {
setSkills(data.skills);
}
}, [data]);
const handleSkills = (skill) => {
setSkills(skill);
};
return (
<div>
<ModalEditSkills
handleSkills={handleSkills}
data={skills}
/>
</div>
);
}
ModalEditSkills.jsx
const ModalEditSkills = ({ data, handleSkills }) => {
const [show, setShow] = useState(false);
const [newData, setNewData] = useState({});
useEffect(() => {
if (data) {
setNewData(data);
}
}, [data]);
const handleClose = () => setShow(false);
const handleShow = () => setShow(true);
const handleSubmitSkills = (e) => {
e.preventDefault();
handleSkills(newData);
setShow(false);
};
return (
<>
<div className="content_header">
<div className="content_header_top">
<div className="header_left">Skills</div>
<div className="header_right">
<Button className="round-btn" onClick={handleShow}>
<i className="fa-solid fa-pencil t-14"></i>
</Button>
</div>
</div>
</div>
<Modal show={show} onHide={handleClose} size="">
<Modal.Header closeButton>
<Modal.Title>Edit Person</Modal.Title>
</Modal.Header>
<Modal.Body>
<SkillEdit data={data} setNewData={setNewData} />
</Modal.Body>
<Modal.Footer>
<Form>
<Button className="btn-skill-complete" onClick={handleSubmitSkills}>
Save
</Button>
</Form>
</Modal.Footer>
</Modal>
</>
);
};
SkillEdit.jsx
const SkillEdit = ({ data, setNewData }) => {
const [inputField, setInputField] = useState([{ skill: "", stars: 0 }]);
const handleAddFields = () => {
setInputField([...inputField, { skill: "", stars: 0 }]);
};
const handleRemoveFields = (index) => {
const values = [...inputField];
values.splice(index, 1);
setInputField(values);
setNewData(values);
};
const handleChangeInput = (index, name, value) => {
const values = [...inputField];
values[index][name] = value;
setInputField(values);
setNewData(values);
};
useEffect(() => {
if (data) {
const setSkills = () => {
setInputField(data);
};
setSkills();
}
}, [data]);
return (
<Form>
<div>
{inputField?.map((inputField, index) => (
<div key={index}>
<Row>
<Col xs={5} md={5}>
<Form.Group as={Col}>
<Form.Control
className="mb-3"
type="text"
id="skill"
name="skill"
value={inputField?.skill}
onChange={(event) =>
handleChangeInput(index, "skill", event.target.value)
}
/>
</Form.Group>
</Col>
<Col xs={4} md={4}>
<div>
<Form.Group>
<ReactStars
type="number"
name="stars"
count={5}
size={24}
id="stars"
onChange={(newValue) =>
handleChangeInput(index, "stars", newValue)
}
emptyIcon={<i className="fa-solid fa-star"></i>}
filledIcon={<i className="fa-solid fa-star"></i>}
value={inputField.stars}
/>
</Form.Group>
</div>
</Col>
<Col xs={3} md={3}>
<div>
<button
type="button"
onClick={() => handleAddFields()}
>
<i className="fa-solid fa-plus"></i>
</button>
<button
type="button"
onClick={() => handleRemoveFields(index)}
>
<i className="fa-solid fa-minus"></i>
</button>
</div>
</Col>
</Row>
</div>
))}
</div>
</Form>
);
};
This took some time for me to work out. I had trouble reproducing and still do, but I noticed a lot of odd behaviour around the stars. In the end, I've figured out its probably this bug in the react-stars package.
Unfortunately, the value prop does not actually control the value after the initial render. So It's like an uncontrolled component. The library therefore, is poor. It hasn't been committed to for 4 years. Usually, if a component is uncontrolled, the developer calls the prop initialValue or defaultValue instead of value, which usually implies the component is controlled. Here, the author has made a mistake. Regardless, in your case, you need controlled mode.
It's possible theres another bug interacting. But I'd start by replacing react-stars as not being able to have controlled mode is extremely poor and it makes it very hard to see the wood through the trees. There is a "solution" in the github thread but its a massive hack -- its using the special key property to remount it every time the value changes.
I went looking for an alternative and much to my surprise a lot of the other libraries are also uncontrolled -- which really sucks. What you could do instead of the hack in the github issue, is make it so the dialog is unmounted when open is false. This would mean each time the dialog opens it resets the value back to that which is held in the parent state. See my bottom code for that solution.
There's good options though here and here but they are part of larger design systems, and its probably overkill to bring in a whole other design system when you have committed to bootstrap. Depending on how early you are in your project though, I'd seriously consider switching to something like MUI. Personal opinion territory, but bootstrap is pretty outdated and the React wrapper and associated community, plus diversity of components, is much smaller. It shows that react-bootstrap is a wrapper on top of old school global CSS files as opposed to material-ui which was built from the ground up in React and has a React based CSS-in-JS solution. When people first start learning react, they often slip into bootstrap because its what they know from non-react dev -- but using a framework like React moves the needle and trade offs.
It's not your problem here, but I feel the need to say it :D. At the same time I'd say don't always take a random internet strangers recommendation and refactor for nothing -- you should research it.
A few other important notes:
If id is not set, you set data to an empty string. If that case ever happened for real, your code would error since accessing data.skills would result in undefined. I would argue that you shouldn't even need to handle this case, since your router setup should be such that there is no mapping between this component and a route without an id. Make sure on your router config the id param is non-optional.
You are copying data.skills into a new state item called skills. It's not a bug per-se but it is a code smell as its not actually necessary. Why not edit the data in the data state directly? Copying state that is fundamentally the same is usually an anti-pattern as you can fall into traps where you are trying to keep 2 bits of state in sync that are supposed to be the same. I think its ok where you do it further down as I believe you are copying it because you want that state not to be committed further up until the user clicks save -- which means its actually fundamentally different state at given times. But that doesnt apply to the top level data vs skills one. Actually, I think the inputField state is also not needed since your "staged" state is held by the parent ModalEditSkills in newData. You could instead get rid of this inputField state and have handleChangeInput, handleAddFields and handleRemoveFields call up into ModalEditSkills to patch newData directly. Then pass that down. This will greatly reduce the surface area for bugs and remove unnecessary effects in SkillEdit.
You are often passing props called set[Something]. Generally, in react, you want to keep to the naming convention of user triggered events beginning with on. The trouble with the former, is it implies that the user action does a certain thing, which makes the component look like its less reusable in other contexts (even though its the same behaviour really, its just incorrect naming).
When setting a state item thats derived partly from its previous value, you should use the callback pattern of setState (which is passed the current value) instead of referencing the state value returned from useState. This avoids bugs to do with accidentally getting a stale value when you update state in a loop or something. React doesn't actually update the value of the state immediately, it gets flushed at the end of the call stack. Using the previous value callback gets around this. Not a problem that will show up in your code, just good practice that you should get in the habit of.
There's a bug where you need to reset the form data back to the data stored in the top component when it opens/closes because currently if you make a change and close dialogue, without clicking save, its still there next time you open it. Its not actually saved to the parent state, its just hanging around in the background (hidden). Its weird UX so I've fixed by adding show to the effect that resets the newData state. If you really wanted it how it was though you can just remove that again from the deps array.
There was also a bug in the way you were patching the state when editing an existing skill. Even though you cloned the skills array by spreading a new one, this only does a shallow clone. The object you spread into the array are the same (as in literally, the same object reference) as the original ones. This meant you were mutating the data prop which is not allowed in react. I've changed to Object.assign to make sure its a proper edited clone. The way this works if everything gets merged from right to left. So by the first param being {}, you start with a brand new object and then you load int the old + new data into it. Libraries like Immer make this easier, you might want to look into it.
I haven't fixed this one as it's kind of up to you but if you were on slow network, there would be a period where you could confuse the user since the data hasn't come back yet but they can open the dialogue and see no skills. You might want to handle that case by showing a loading display instead of the rest of the app whilst its in flight. You could make the default state of the top level data state null and then only populate it when the request comes back like you do now. Then in the top level render you'd check for null and return some loading display instead of ModalEditSkills. Similar stuff would happen if the network errored. You might also want to have some new state that says if an error happened (instead of just logging), and check that as well and display the error page.
Heres the code with my proposed changes (minus the library change, you'd still need to do that if you cared enough).
And heres a code sandbox with it working: https://codesandbox.io/s/wispy-meadow-3ru2nq?file=/src/App.js (I replaced the network call with static data for testing, and I dont have your icons).
I hope this feedback helps you on your react journey!
const EditPerson = () => {
const [data, setData] = useState({skills: []});
const { id } = useParams();
useEffect(() => {
const fetchData = async () => {
const docRef = doc(db, "person", id);
try {
const docSnap = await getDoc(docRef);
setData(docSnap.data());
} catch (error) {
console.log(error);
}
};
fetchData().catch(console.error);
}, []);
const handleSkillsChanged = (skills) => {
setData(data => ({...data, skills}));
}
return (
<div>
<ModalEditSkills
onSkillsChanged={handleSkillsChanged}
data={data.skills}
/>
</div>
);
}
const ModalEditSkills = ({ data, onSkillsChanged}) => {
const [show, setShow] = useState(false);
const [newData, setNewData] = useState([]);
useEffect(() => {
setNewData(data);
}, [data, show]);
const handleClose = () => setShow(false);
const handleShow = () => setShow(true);
const handleSkillChange = (index, name, value) => {
setNewData(prevValues => {
const newValues = [...prevValues]
newValues[index] = Object.assign({}, newValues[index], { [name]: value });
return newValues
});
}
const handleSkillAdded = () => {
setNewData(prevValues => [...prevValues, { skill: "", stars: 0 }]);
}
const handleSkillRemoved = (index) => {
setNewData(prevValues => {
const newValues = [...prevValues];
newValues.splice(index, 1);
return newValues
});
}
const handleSubmitSkills = (e) => {
e.preventDefault();
onSkillsChanged(newData);
setShow(false);
};
return (
<>
<div className="content_header">
<div className="content_header_top">
<div className="header_left">Skills</div>
<div className="header_right">
<Button className="round-btn" onClick={handleShow}>
<i className="fa-solid fa-pencil t-14"></i>
</Button>
</div>
</div>
</div>
{show && (
<Modal show={show} onHide={handleClose} size="">
<Modal.Header closeButton>
<Modal.Title>Edit Person</Modal.Title>
</Modal.Header>
<Modal.Body>
<SkillEdit
data={newData}
onSkillChanged={handleSkillChange}
onSkillAdded={handleSkillAdded}
onSkillRemoved={handleSkillRemoved}
/>
</Modal.Body>
<Modal.Footer>
<Form>
<Button
className="btn-skill-complete"
onClick={handleSubmitSkills}
>
Save
</Button>
</Form>
</Modal.Footer>
</Modal>
)}
</>
);
};
const SkillEdit = ({ data, onSkillChanged, onSkillRemoved, onSkillAdded}) => {
return (
<Form>
<div>
{data?.map((inputField, index) => (
<div key={index}>
<Row>
<Col xs={5} md={5}>
<Form.Group as={Col}>
<Form.Control
className="mb-3"
type="text"
id="skill"
name="skill"
value={inputField?.skill}
onChange={(event) =>
onSkillChanged(index, "skill", event.target.value)
}
/>
</Form.Group>
</Col>
<Col xs={4} md={4}>
<div>
<Form.Group>
<ReactStars
type="number"
name="stars"
count={5}
size={24}
id="stars"
onChange={(newValue) =>
onSkillChanged(index, "stars", newValue)
}}
emptyIcon={<i className="fa-solid fa-star"></i>}
filledIcon={<i className="fa-solid fa-star"></i>}
value={inputField.stars}
/>
</Form.Group>
</div>
</Col>
<Col xs={3} md={3}>
<div>
<button
type="button"
onClick={onSkillAdded}
>
<i className="fa-solid fa-plus"></i>
</button>
<button
type="button"
onClick={() => onSkillRemoved(index)}
>
<i className="fa-solid fa-minus"></i>
</button>
</div>
</Col>
</Row>
</div>
))}
</div>
</Form>
);
};
I'm building a page that will render a dynamic number of expandable rows based on data from a query.
Each expandable row contains a grid as well as a button which should add a new row to said grid.
The button needs to access and update the state of the grid.
My problem is that I don't see any way to do this from the onClick handler of a button.
Additionally, you'll see the ExpandableRow component is cloning the children (button and grid) defined in SomePage, which further complicates my issue.
Can anyone suggest a workaround that might help me accomplish my goal?
const SomePage = (props) => {
return (
<>
<MyPageComponent>
<ExpandableRowsComponent>
<button onClick={(e) => { /* Need to access MyGrid state */ }} />
Add Row
</button>
<MyGrid>
<GridColumn field="somefield" />
</MyGrid>
</ExpandableRowsComponent>
</MyPageComponent>
</>
);
};
const ExpandableRowsComponent = (props) => {
const data = [{ id: 1 }, { id: 2 }, { id: 3 }];
return (
<>
{data.map((dataItem) => (
<ExpandableRow id={dataItem.id} />
))}
</>
);
};
const ExpandableRow = (props) => {
const [expanded, setExpanded] = useState(false);
return (
<div className="row-item">
<div className="row-item-header">
<img
className="collapse-icon"
onClick={() => setExpanded(!expanded)}
/>
</div>
{expanded && (
<div className="row-item-content">
{React.Children.map(props.children, (child => cloneElement(child, { id: props.id })))}
</div>
)}
</div>
);
};
There are two main ways to achieve this
Hoist the state to common ancestors
Using ref (sibling communication based on this tweet)
const SomePage = (props) => {
const ref = useRef({})
return (
<>
<MyPageComponent>
<ExpandableRowsComponent>
<button onClick={(e) => { console.log(ref.current.state) }} />
Add Row
</button>
<MyGrid ref={ref}>
<GridColumn field="somefield" />
</MyGrid>
</ExpandableRowsComponent>
</MyPageComponent>
</>
);
};
Steps required for seconds step if you want to not only access state but also update state
You must define a forwardRef component
Update ref in useEffect or pass your API object via useImerativeHandle
You can also use or get inspired by react-aptor.
⭐ If you are only concerned about the UI part (the placement of button element)
Portals provide a first-class way to render children into a DOM node that exists outside the DOM hierarchy of the parent component.
(Mentioned point by #Sanira Nimantha)
I'm making a Nextjs flashcard app. I'm passing a deck structure like this:
const deck = {
title: 'React 101',
flashcards: [flashcardOne, flashcardTwo],
};
as props to the Deck component. This component shows the first card in flashcards and a "next" button to increment the index and showing the next card in flashcards.
The Card component is very simple and shows the front and the back of the card depending of the state front.
This is what I got so far and it's working but if I click "next" when the card is showing the answer (flashcard.back), the next card is going to appear with the answer. And I'm not sure why, isn't the Card component re rendering when I click "next"? And if the component re renders, front is going to be set to true?
export default function Deck({ deck }) {
const [cardIndex, setCardIndex] = useState(0);
const { title, flashcards } = deck;
return (
<div className={styles.container}>
<main className={styles.main}>
<h1 className={styles.title}>{title}</h1>
{cardIndex < flashcards.length ? (
<>
<div className={styles.grid}>
<Card flashcard={flashcards[cardIndex]} />
</div>
<button onClick={() => setCardIndex((cardIndex) => cardIndex + 1)}>
Next
</button>
</>
) : (
<>
<div>End</div>
<button>
<Link href='/'>
<a>Go to Home</a>
</Link>
</button>
<button onClick={() => setCardIndex(0)}>Play again</button>
</>
)}
</main>
</div>
);
}
export function Card({ flashcard }) {
const [front, setFront] = useState(true);
return (
<>
{front ? (
<div
className={`${globalStyles.card} ${styles.card}`}
onClick={() => setFront(false)}
>
<p className={styles.front}>{flashcard.front}</p>
</div>
) : (
<div
className={`${globalStyles.card} ${styles.card}`}
onClick={() => setFront(true)}
>
<p className={styles.back}>{flashcard.back}</p>
</div>
)}
</>
);
}
When state changes, the card will re-render, but it will not re-mount. So, existing state will not be reset.
Call setFront(true) when the flashcard prop has changed:
const [front, setFront] = useState(true);
useLayoutEffect(() => {
setFront(true);
}, [flashcard]);
I'm using useLayoutEffect instead of useEffect to ensure front gets set ASAP, rather than after a paint cycle (which could cause flickering).
You can also significantly slim down the Card JSX:
export function Card({ flashcard }) {
const [front, setFront] = useState(true);
const face = front ? 'front' : 'back';
return (
<div
className={`${globalStyles.card} ${styles.card}`}
onClick={() => setFront(!front)}
>
<p className={styles[face]}>{flashcard[face]}</p>
</div>
);
}
Okay, I guess I had the same issue. Since you're using functional components, and you're re-using the same component or in better words, you're not unmounting and remounting the component really, you're just changing the props, this happens. For this, you need to do useEffect() and then setFront(true).
Here's the code I used in my App.
useEffect(() => {
setFront(true);
}, [flashcard]);
This is what I have used in my Word.js file.