Props and State ...Of Components - 401-advanced-javascript-aimurphy/seattle-javascript-401n13 GitHub Wiki
If components are like functions, props are the input. The golden rule of props in React is that:
All React components must act like pure functions with respect to their props.
this means no mutating the inputs--inputs are read-only, bro.
The simplest way to define a component is to write a JavaScript function:
function Welcome(props) {
return <h1>What's up, {props.name}</h1>;
}
const element = <Welcome name="my dude" />;
ReactDOM.render(
element,
document.getElementById('root')
);
Why this works?: because it accepts a single props object argument with data and returns a React element. We call such components “function components” because they are literally JavaScript functions.
You can also use an ES6 class to define a component:
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
more about fn vs class styles
you can get more examples of composing, as well as extracting, components here 🖥🖱click!
free up those resources when you're done with them
Nobody speaks to the wizard! You gotta use the proper avenues of communication: setState()
. If you're not in the constructor, you're not setting this.state
in any shape or form, so to recap:
this.state.comment = 'Hello';
this.setState({comment: 'Hello'});
If you need to make multiple updates on the states and properties, try and do it with a function, since they can update asynch and might not reflect what you're hoping for.
this.setState((state, props) => ({
counter: state.counter + props.increment
}));
this.setState(function(state, props) {
return {
counter: state.counter + props.increment
};
});
more classy infos on states here😎 will also expand on the beauty of setState
React events are named using camelCase, rather than lowercase. With JSX you pass a function as the event handler, rather than a string. For example, the HTML:
<button onclick="activateLasers()"> --becomes--> <button onClick={activateLasers}>
//the rest is the same
Activate Lasers
</button>
Another difference is that you cannot return false. Instead we preventDefault()
more event wrangling here yeehaw! 🐄🤠
forms are a bit of a special case in React since they naturally keep some internal state. Elements like <input>
, <textarea>
, and <select>
typically maintain their own state and update it based on user input. In React, mutable state is typically kept in the state property of components, and only updated with setState(). But say you want to be able to handle submissions a certain way and have access to the data the user enters in to the form.
We can combine the two by making the React state be the “single source of truth”. Then the React component that renders a form also controls what happens in that form on subsequent user input. An input form element whose value is controlled by React in this way is called a “controlled component”.
sources: