// USE STATE
console.log(useState("Hello world")); //returns arraz
const value = useState(1)[0];
const handler = useState(1)[1];
ReacAdvanced2020 tutorial 1useState
//
import React, { useState } from "react";
console.log(useState());
EXAMPLE:
import React, { useState } from 'react';
// starts with use
// component must be uppercase
// invoke inside function/component body
// don't call hooks conditonally
const UseStateBasics = () => {
// console.log(useState());
// const value = useState()[0];
// const handler = useState()[1];
// console.log(value, handler);
const [text, setText] = useState('random title');
const handleClick = () => {
if (text === 'random title') {
setText('hello world');
} else {
setText('random title');
}
};
return (
{text}
);
};
export default UseStateBasics;
//STAE
//data that a component mantains. Can't change its value. Props cannot be changed
import React, {Component} from 'react'
import React, {Component} from 'react'
//STATE: needs to be a class based component
//needs a constructor that initializes values / parts of a class
//if not used {Component}, need to use down here React.Component
class App extends Component {
constructor(){
super()
this.state ={
name: "Alberto",
age: "38",
answer: "yes",
isLoggedIn: true
}
}
render(){
let wordDisplay
if (this.state.isLoggedIn) {
wordDisplay = "in"
}else{
wordDisplay = "out"
}
return (
<div>
<h1>{this.state.name}</h1>
<h1>{this.state.age} years old</h1>
<p>Is state necessary? {this.state.answer}</p>
<p>Are you logged in/out? {wordDisplay}</p>
</div>
)
}
}
export default App;
// CHANGING STATE - SEE HANDLING EVENTS<
//CHANGING STATE
import React from 'react'
class App extends React.Component {
constructor(){
super()
this.state ={
count: 0
}
this.handleClick = this.handleClick.bind(this)
}
handleClick(){
console.log("I'm working")
//this.setState({count: 1}) //when using set state you neet to binde it. See line above
this.setState(prevState => {
return {
count: prevState.count + 1
}
})
}
render(){
return (
<div>
<h1>{this.state.count}</h1>
<button onClick={this.handleClick}>Change</button>
</div>
)
}
}
export default App;