Well, it seems the main problem it tries to solve is - how to use state inside functional components.
Functional... what?
Ok, lets start from the beginning:
Usually to build the component with React you should use the following syntax:
class HelloMessage extends React.Component {
render() {
return (
<div>;
Hello {this.props.name}
</div>
);
}
}
It also called the class syntaxThe Interesting thing is - this is not the only way. There is another way to create react component, it called functional :
function Example(props) {
return (
<div>;
Hello {this.props.name}
</div>
);
}
This way is much more simpler and clear and testable, because - it is just javascript function!BUT! (There is always but) - one of the limitations of functional components is - that here you cannot use the "state" feature of React.
State - it is inner data of the component which is not accessible from the parent
class UserForm extends React.Component {
constructor(props){
super(props);
this.state = {
username:'',
lastname: ''
};
}
render() {
return (
<form>
username: <input value={this.state.username}/> <br/>
lastname: <input value={this.state.lastname}/>
</form>
);
}
}
ReactDOM.render(
<UserForm />,
document.getElementById('user-form')
);
So now (from React 16.8 and later) you can use state feature event inside functional components (Yes You Can!)- by using following syntax:
import React, { useState } from 'react';
export default function Example() {
const [userModel, setUserModel] = useState({username:'ss', lastname:'dd'});
return (
<form>
username: <input value={userModel.username}/> <br/>
lastname: <input value={userModel.lastname}/>
</form>
);
}
Note that "setUserModel" is for modify the state:
<button onClick={()=>setUserModel({username: 'shlomo', lastname: 'shlomovitz'})}/>click</button>
Pretty Cool, huh?
No comments:
Post a Comment