Hope the title makes sense, it's a bit of a confusing one.
I have built a quiz tool for language learning. It has an array of components, and as users get questions right it progresses through to the next questions. This works fine (and is live here: https://comhradh.netlify.app/quiz), but currently the list of questions exists within that component, and I want to be able to call it in different places, passing it a different array of question components each time.
What I've tried so far is this: I have three components - a grandparent, parent, and child one. The grandparent - "Lesson.js" calls the parent - "Quiz.js" - which in turn pulls things from the child component - "TestComponents.js". Quiz.js takes as a prop a questions array, with a bunch of components which all get rendered by TestComponents component.
However, I need each of the objects in the questions array to pick up a handleCorrect prop from Quiz.js - the parent component - which doesn't exist in Lesson.js - the grandparent one.
I'll show you what I mean:
Grandparent - Lesson.js Calls this:
<Quiz
questions={[
<Qtranslate1
Q="Tha mi beag"
A={["I am small", "I'm small"]}
handleSubmit={true}
header="default"
/>,
]}
/>
But in Quiz.js, I there is a handleCorrect function:
const handleCorrect = () => {
setIndex((prevIndex) => prevIndex + 1);
};
Which is meant to go through each of the questions being passed to the Quiz.js component as user's complete them. Because that handleCorrect() function only exists in Quiz.js, I can't pass it as a prop to the components objects when I initially pass them as a prop to the Quiz.js component.
In my first version, where the questions array just existed as a constant within Quiz.js, each of them took this argument: handleCorrect={() => handleCorrect()} which worked fine.
I have tried to pass the questions to the Quiz component without a handleCorrect prop, and then go through them map through them and add it in oncce they're in the Quiz component, but I get this error:
TypeError: Cannot add property handleCorrect, object is not extensible
Is there a way to do this?
What you are trying to do is changing the objects which are coming from the props(Grand Parent). It's not Possible. Instead you can deep copy the array and manipulate the array and send it to the child Component.
You can do this while mounting the Quiz component.
useEffect(() => {
var tempQuestions = props.questions
tempQuestions = JSON.parse(JSON.stringify(tempQuestions))
/* You can now manipulate this data and send it across child components */
},[])