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
JavaScript
x
22
22
1
import React, { useState } from 'react';
2
import './style.css';
3
import Comp from './Component.js';
4
export default function App() {
5
const [results, setResults] = useState([]);
6
7
results.length = 20;
8
results[3] = 'kiss';
9
results[2] = [12, 454, 45];
10
console.log(results);
11
12
return (
13
<div>
14
<h1>Hello StackBlitz!</h1>
15
<p>Start editing to see some magic happen :)</p>
16
<Comp result={results[5]}/>
17
<button onClick={() => console.log(results)}> SHOW </button>
18
</div>
19
);
20
}
21
22
the component
JavaScript
1
14
14
1
import React, { useState } from 'react';
2
3
const Comp = ({result}) => {
4
result = 1
5
console.log(result)
6
return (
7
<div>
8
hhhhh
9
</div>
10
);
11
}
12
13
export default Comp
14
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 .