I have a code in which I need to pass a const inside the useState can someone help??
The below code is in class constructor I want to convert that into functional component
Class Component:
constructor(props){
super(props);
const {id, name, email} = props.location.state.contact;
this.state={
id,
name,
email
}
How to do this above in functional component?
CodePudding user response:
I believe you can do the following
function Component(props) {
const [state, setState] = useState(props.location.state.contact);
// state will have id, name, and email
return <></>
}
Read more about usage of hooks here
CodePudding user response:
You can add a default value for the use state hook. Just pass the props.
function Component(props) {
const {location:{ state: { contact: { id, name, email } } }} = props;
const [state, setState] = useState({id, name, email});
}
If you want to reset the state on the prop changes, set a useEffect
hook with the respective props in the dependency array, and set the state with the new values.
CodePudding user response:
You can use it as function component
like this
import React, {useState} from 'react';
function myComponent(props) {
const {id, name, email} = props.location.state.contact;
const [stateValue, setStateValue] = useState({id, name, email});
return (
....
)
}
export default myComponent;
CodePudding user response:
You can get props by destructuring inside the function component without using useState
import React, { useState } from 'react';
function Test(props) {
// destructuring
const { id, name, email } = props;
return (
<div>
...
</div>
)
}
export default Test;
But if you want to use useState
:
import React, { useState } from 'react';
function Test(props) {
// destructuring
const [state, setState] = useState(props.location.state.contact);
return (
<div>
...
</div>
)
}
export default Test;