Yash Tailor
Yash Tailor

Reputation: 13

Adding state to an external variable in React

Suppose I have a file called Columns.js and I am exporting an object cols = {//some data} in it. Now, say I am importing that object in file Widget.js. Now, can I add that variable to the state of the react component?

I want to do this way as the object is too big. Also, i have tried cloning it but it doesn't work.

Columns.js

const cols = {A:'a',B:'b'}
export default cols;

Widget.js

import cols from './Columns';
export default function Widget(){
// here i want to make my variable cols have a state

//some code which uses cols and changes it
}

Upvotes: 0

Views: 205

Answers (1)

Kiril
Kiril

Reputation: 301

It's as easy as using spread syntax for the object to copy it inside state object in your useState call (if we talk about functional component). So the code should look like this:

import cols from './Columns';
export default function Widget(){
// here i want to make my variable cols have a state
  const [state, setState] = useState({...cols});

//some code which uses cols and changes it
}

Now your state variable holds the same data as the cols and you can use it in your ui and change with setState.

Upvotes: 1

Related Questions