Reputation: 95
I'm creating a Multi Dropdown component in React.JS, I want to clone a variable (selectedData) from App.js into a component. But when I try to clone data there is always an error "Cannot assign to read only property 'selectedData' of object"
import React from 'react';
import MultiDropdown from './Components/MultiDropdown/MultiDropdown.component';
import { allOptions } from './Utils/DummyData';
import "./App.css";
const App = () => {
var clonedData = [
{ value: 'Normal😐', label: 'Normal😐' },
{ value: 'Angry😡', label: 'Angry😡' },
{ value: 'Love😍', label: 'Love😍' },
]
return(
<div className='app'>
<MultiDropdown
data={allOptions}
placeholder="Select Options"
selectedData={clonedData}
// value={clonedData}
/>
<button onClick={() => console.log("Selected", clonedData)}>Click to See SelectedData</button>
</div>
)
}
export default App;
I wanted to clone variable CloneData, that passed on selectedData, I use this function to clone data
Here's my components code :
export default function MultiDropdown(props: Props): React.Node {
const [data, setData] = React.useState(props.selectedData ? props.selectedData.map(opt => opt.value) : []);
React.useEffect(() => {
props.selectedData = data;
}, [data, props]);
return (
<div>
<Select
ref={props.selectedData}
{...DropDownProps(props, data, SelectOption)}
onChange={selected => setData(selected.map(opt => opt.value))}
/>
{data.map(opt => (<ListContainer key={opt} opt={opt} data={data} set={setData} />))}
</div>
);
}
I'm trying cloning my variable on useEffect
Thankyou guys!
Upvotes: 0
Views: 286
Reputation: 188
You can't directly change props that come to your component but there is a way:
You can create a useState
to store your clonedData
pass the state and the function that changes that state.
import React from 'react';
import MultiDropdown from './Components/MultiDropdown/MultiDropdown.component';
import { allOptions } from './Utils/DummyData';
import "./App.css";
const App = () => {
const [clonedData , setClonedData] = React.useState([
{ value: 'Normal😐', label: 'Normal😐' },
{ value: 'Angry😡', label: 'Angry😡' },
{ value: 'Love😍', label: 'Love😍' },
]);
return(
<div className='app'>
<MultiDropdown
data={allOptions}
placeholder="Select Options"
selectedData={clonedData}
changeSelectedData={setClonedData} // pass the setter function.
// value={clonedData}
/>
<button onClick={() => console.log("Selected", clonedData)}>Click to See SelectedData</button>
</div>
)
}
export default App;
Then use this useState
hook rather than defining it in the component. Because there is no way to directly pass anything defined in the child component to the parent component
Upvotes: 1