I’m trying to give one component the array value at a certain index and assign a value that i want from the child component.
I want it like this because I’m trying to do a survey app and the number of question can be different. this is just a little test that concludes what I want.
the base Component
import React, { useState } from 'react'; import './style.css'; import Comp from './Component.js'; export default function App() { const [results, setResults] = useState([]); results.length = 20; results[3] = 'kiss'; results[2] = [12, 454, 45]; console.log(results); return ( <div> <h1>Hello StackBlitz!</h1> <p>Start editing to see some magic happen :)</p> <Comp result={results[5]}/> <button onClick={() => console.log(results)}> SHOW </button> </div> ); }
the component
import React, { useState } from 'react'; const Comp = ({result}) => { result = 1 console.log(result) return ( <div> hhhhh </div> ); } export default Comp
here is a place I set it up => https://stackblitz.com/edit/react-mfpk5f?file=src%2FApp.js,src%2FComponent.js
every suggestion is highly appreciated!
Advertisement
Answer
parent componentHere i have tried a way to find solution , just keep a callback function in child component and call a function of parent component inside child so that u can pass data to it .