react Flashcards
react: In jsx, to write a css class attribute, you must write
className=”cssClass”
react: A component “mounting” means
it is rendering for the first time
react: The three mounting methods that get called in order when you call ReactDOM.render() are
componentWillMount: right before the component renders. You CAN call this.setState() in this. Being deprecated, so don’t use.
render: the render function runs and injects the JSX
componentDidMount: right after the render function runs. Usually used to make API call for initial data, can use constructor. Also used to
react: componentDidMount only gets called
AFTER the very first rendering of a component. Using set interval to run ReactDOM.render() again will not retrigger it.
react: componentWillReceiveProps will only get called if
a component is being passed in props
react: componentWillReceiveProps automatically gets passed one argument which is
an object called ‘nextProps’ which is the value of the prop that will be passed in
react: componentWillReceiveProps is an opportunity to
do something based on the new props a component is going use before render
react: files with jsx written in them must be
compiled before sent to browser
react: If a JSX snippet takes up multiple lines, you must
wrap it in parentheses.
react: JSX must be
wrapped in one outermost element.
react: ReactDOM.render() takes the arguments
component and location to inject it
ie
ReactDOM.render(-h1>Hello world-/h1>, document.getElementById(‘app’));
react: To render a JSX expression into the template, type
ReactDOM.render(-h1>Hello world-/h1>, document.getElementById(‘app’));
react: if you call
ReactDOM.render(hello, document.getElementById(‘app’));
and then again
ReactDOM.render(hello, document.getElementById(‘app’));
it will
do nothing because react will only render the same component in the same location again if it has changed
react: In JSX, self closing tags like input and img must
have a closing slack ie img />
react: To evaluate code inside of JSX,
wrap it in {} ie -h1>{2 + 3}-/h1> and the return will be rendered
react: The JSX in your file can access
all the variables in the environment
const theBestString = ‘tralalalala i am da best’;
ReactDOM.render(-h1>{theBestString}-/h1>…
react: event listeners (like onclick) in JSX must
be written in camelCase
onClick={funcName}
react: To manipulate the element that sent an event, use
function functionName(e) { const element = e.target }
ie the -img> src will change.
function changeImage(e) { e.target.setAttribute('src', 'https://url.com'); }
react: in JSX, you cannot
write if statements in the {} braces
js: To write a ternary, type
x > 10 ? y : z
js: To write a conditional using &&, type
x > 10 && functionName()
note: It is the same as a ternary but with no else
React: JSX can be rendered even if it is a
list of JSX objects.
const liArray = [ -li>item 1-/li>, -li>item 2-/li>, -/li>item 3-/li> ];
-ul>{liArray}-/ul>
React: To use map to make a list of JSX objects, type
const myJSXArray = myArray.map((item, key) => -li key={key}>{item}-/li> );
React: The steps for rendering JSX are
A JSX element renders.
The entire virtual DOM updates.
The virtual DOM “diffs,” comparing its current self with its previous self.
Part of the real DOM updates.
The screen looks different than it used to.
js: Class and Component names must be written in
UpperCamelCase
js: importing and exporting modules
https://www.youtube.com/watch?v=Jqn_wjkSZwo
js: To import a file from a filepath instead of from the environment,
you must add the ./ to “./FileName” so node looks in the filepath.
Note, if there is no file type extension, node assumes it is .js
js: To export something from your file (aka named export), type
export before any top level variable, function, or class ie
export const myVar = “string”
then to import from same directory, type
import { myVarName, myFunctionName } from ‘./FileName’;
note: Curly brackets needed for named exports because there can be multiple, but default exports don’t need curly brackets
note: even if there is only one named export, you still need the curly brackets
React: When sending in props to a component, the values that are not strings must
be in {} curly braces
React: When passing an event handler function into a component as a prop, name the prop
the same as the name of the function.
ie handleClick() {}
the prop:
onClick = {this.handleClick}
note: onClick is only a special event listener when on regular html elements. On components it behaves just like any prop.
React: The name convention for naming event handler functions is
handleClick, handleMouseOver etc.
react: If a component has more than one child between its JSX tags, then
this.props.children will return those children in an array. But if a component has only one child it will return the single child, not wrapped in an array.
react: To give a component default props that will get called if this.props.propName was called but never passed in, type
class MyComponent extends React.Component { render() { return -h1>{this.props.text}-/h1>; } }
MyComponent.defaultProps = { text: ‘string’ };
react: To create a constructor and set initial state, type
constructor(props) {
super(props);
this.state = { mood: ‘decent’ };
}
ES6: In between functions of a class
do not put a comma
react: whenever you define an event handler that uses this, you must
add this.methodName = this.methodName.bind(this) to your constructor function.
react: this.setState automatically
calls render
react: Stateless child components should only
update a parent component using a function the parent passed down to it through props
react: To choose which component to add ReactDOM.render() to, you need to choose
the highest level one, which calls all the other components in its render function
react: A component should use state to store
information that the component itself can change.
it should never change its props. If a child needs to change it’s props, it needs to get a handler function from the parent as a prop to call, not change it on its own.
react: Every event handler automatically passes in
an event argument into the function
onClick = {this.props.onClick}
in the parent function you can write
handleClick(e) { let value = e.target.value }
react: When an event is happening in a child component, that will then change a parent components state, often
you will create a function in the child component to process the event into a properly formatted value (e.target.value), and then call this.props.parentsFunction(formattedValue) from there, for clarity
react: if you are repeating {this.props.propName} in the render function a lot, might as well
create a variable let propName = this.props.propName in the render function and just use {propName}
react: a common pattern is
A stateful component class defines a function that calls this.setState. (Parent.js, lines 15-19)
The stateful component passes that function down to a stateless component. (Parent.js, line 24)
That stateless component class defines a function that calls the passed-down function, and that can take an event object as an argument. (Child.js, lines 10-13)
The stateless component class uses this new function as an event handler. (Child.js, line 20)
When an event is detected, the parent’s state updates. (A user selects a new dropdown menu item)
The stateful component class passes down its state, distinct from the ability to change its state, to a different stateless component. (Parent.js, line 25)
That stateless component class receives the state and displays it. (Sibling.js, lines 5-10)
An instance of the stateful component class is rendered. One stateless child component displays the state, and a different stateless child component displays a way to change the (Parent.js, lines 23-26)
react: Double curly braces is just
an object literal inside of the braces that tell jsx to read as javascript
react: you can set styles by
const styles = {background: ‘lightblue’, color: ‘darkred’}
and style={divStyle}
note: Its cool to name the style object according to the element it will be styling
react: In css style names are written in hyphenated lowercase, in react they are written as
camelCase
ie {fontSize: ‘50px’}
note the values are usually strings, but if you don’t use a string, it will assume you are using ‘px’
react: Its common to keep your styles in a styles file like
styles.js
const fontFamily = 'Comic Sans MS, Lucida Handwriting, cursive'; const background = 'pink url("https://media.giphy.com/media/oyr89uTOBNVbG/giphy.gif") fixed'; const fontSize = '4em'; const padding = '45px 0'; const color = 'green';
export const styles = { fontFamily: fontFamily, background: background, fontSize: fontSize, padding: padding, color: color };
react: A presentational component looks like
a class with just a render function and a lot of html like JSX, and no ReactDOM.render() function
a container component uses the presentational component, and has a lot of functions
react: if a component has a lot of functions, it shouldn’t
also have a lot of html like JSX
react: If a component only has a render function, it can be rewritten as a
function
react: To rewrite a stateless presentational component as a function, type
class MyComponent extends React.Component { render() { return ... } }
to (keep it UpperCamelCase)
const MyComponent = () => { return ... }
or if theres a props being passed in const MyComponent = (props) => { return ... }
react: To make a component cause a console warning if a certain prop is not passed in
propName: React.PropTypes.string.isRequired,
react: a propType is
a validation you can perform on all of the props passed into a component. Adding this object to the component file after the class declaration.
MyComponent.propTypes = { message: React.PropTypes.string, style: React.PropTypes.object, isMetric: React.PropTypes.bool, miles: React.PropTypes.number, milesToKM: React.PropTypes.func, races: React.PropTypes.array, }
note: add .isRequired to raise a console error when a prop is not passed in.
ie
message: React.PropTypes.string.isRequired,
Note: This works the same way for functional components
react: The attributes input field should have are
onChange={this.handleChange} value={this.state.inputField}
react: If you call ReactDOM.render() on the same component twice, the mounting lifecycle methods will
only run the first time. (except render will rerun if something changes)
react: The updating lifecycle functions are
componentWillReceiveProps: Will only run if the component is being passed in props. Needs a nextProps parameter. Opportunity to do something based on the new props a component is going to render. Will become getDerivedStateFromProps.
shouldComponentUpdate: Opportunity to decide whether or not you want a component to update after state change or not by returning true or false. Requires two arguments, nextProps and nextState.
componentWillUpdate: Requires two arguments, nextProps and nextState. It cannot call this.setState(). Meant for doing DOM manipulations outside of react, interacting with an API. Being deprecated.
componentDidUpdate: Requires two arguments, prevProps and prevState, which allows you to compare current to past. Usually call APIs from here.
react: componentWillReceiveProps automatically gets passed one argument called
an object called ‘nextProps’ which is the value of the prop that will be passed in
componentWillReceiveProps: function (nextProps) {
console.log(nextProps.text) //will return “Hello world”
}
ReactDOM.render(
-Example text=”Hello world” />, document.getElementById(‘app’)
);
react: To ensure that the component renders properly before the api data returns
set up the initial state and default props
react: componentWillUnmount
requires two arguments, prevProps, prevState. Gets called when UI rerenders without this component, or user leaves website or closes their web browser
rn: You must render your jsx inside
View tags -View>-/View>
note: They work like divs
rn: To use a text input, type
-TextInput onChangeText={(text) => {this.setState({name: text})}} />
rn: To have a scrollable View, you must
put ScrollView tags inside View tags
rn: To make a button, type
-Button onPress={this.handleSubmit}>String-/Button>
rn: Styles must be written
into a Stylesheet object like const styles = StyleSheet.create({ container: { flex: 1, alignItems: 'center', justifyContent: 'center', paddingTop: Constants.statusBarHeight, backgroundColor: '#ecf0f1', }, paragraph: { marginTop: 24, }, });
and then called like style={styles.paragraph}
rn: The events for react native are
onPress
onLongPress: press and hold a view for a time
onChangeText: for TextInput changes
rn: To make an alert, type
import { Alert } from ‘react-native’;
in function
Alert.alert(‘alert title’, ‘alert body’)
rn: You cannot access the event object
from functions
rn: To render a list from an API in a press handler, type
handlePress() { return fetch('https://url.json') .then((response) => response.json()) .then((responseJson) => { this.setState({movies: responseJson.itemArray}) }) }
render() { let itemList = this.state.movies.map( (val, key) => { return {val.title} })
{itemList}
react: to make a video component
either use this and copy oak, where the video plays in full width which ever orientation your phone is in, over black background, and have a skip button on top right, and clickin on video pauses, it. https://medium.com/@kalen7/build-this-simple-video-player-with-react-native-and-expo-to-tell-a-multi-part-story-part-3-48f3ce1664f6
or use this, but the full screen doesnt work properly.
https://www.youtube.com/watch?v=X-RoXqCoHK0
this guy has a better ui
https://www.youtube.com/watch?v=1WtL1rNOLcg
react: to make navigation use
https: //www.youtube.com/watch?v=_XZqafNubyQ
https: //www.youtube.com/watch?v=5f5VEEmMSyE
rn: in react native dont forget
use Text, and View instead of html tags
import * as React from ‘react’ and
to type: import { Text, View, StyleSheet } from ‘react-native’;
text-transform is not available
padding: ‘20px 40px’, does not work. Use paddingHorizontal and paddingVertical
use button from: import { Button } from ‘react-native-elements’; because it allows for buttonStyle={styles.buttonStyles} and textStyle={styles.textStyles} . Normal button from react-native does not.
use fontWeight: ‘bold’ instead of 700
register new functions in the constructor
rn: To make a box shadow, type
shadowOffset:{ width: 10, height: 10, },
shadowColor: ‘black’,
shadowOpacity: 1.0,
shadowRadius: 7,
rn: its a bad idea to spread
items from top to bottom using margins, I should use column flex items so that it spreads for bigger phones.
rn: To make a ScrollView horizontal, type
-ScrollView
horizontal={true}
>
rn: you should not use this.setState() in
componentDidMount
js: To append to end of list in place, type
myArray.push(item)
to not do it in place, and actually return a new array use myArray.concat(item)
js: to make a for loop in js, type
for (let item of [1,2,3]) {
console.log(item);
}
react: It seems registering functions in the constructor is only necessary if you
will be sending them as props? Can I attach new functions to self at will if I am using them in the same component? Like, if the function only ever gets called from a neighboring function.
This is an example from React.js website :
class Timer extends React.Component { constructor(props) { super(props); this.state = { seconds: 0 }; }
tick() { this.setState(prevState => ({ seconds: prevState.seconds + 1 })); } componentDidMount() { this.interval = setInterval(() => this.tick(), 1000); } componentWillUnmount() { clearInterval(this.interval); }
render() { return ( -div> Seconds: {this.state.seconds} -/div> ); } }
ReactDOM.render(, mountNode);
react: It would be convenient to set the whole body of the app to become a
spinner if ever a state variable is set to loading when I send an API request so its easier for me to show a spinner when loading by doing this.setState instead of manually
react: If you name a file index.js
you can import it with the path to it, but without writing its actual name
import name from “./folder” // this automatically opens index.js
redux: The basic steps of redux are
You call an action from the component where you originally had the fetch request to get posts.
That action in actions/postActions.js calls the fetch and gets the posts. Then it calls dispatch which sends the return of that fetch into the reducer with a “type” of reducer you want to call
Then the reducer is where you combine the new post data with the initial state (set in the reducer) and then it returns as a ready to use new state.
Then to use that new state in your component, you need to add code to your component that maps the state from the reducer to props, so you can call this.props.itemFromReducerMadeState
the root reducer is just boilerplate
https://youtu.be/93p3LxR9xfM?t=1350
react: To send a parameter back in an onPress function
in element
onPress={e => this.props.onPress(e, ‘param’)}
Note: Learn these functions
in parent
handlePress(e, param1) {
console.log(param1)
}
react: You should declare your functions in the constructor to add .bind(this) because
using arrow functions (that use the enclosing ‘this’) are less performant/slower.
https: //medium.com/@charpeni/arrow-functions-in-class-properties-might-not-be-as-great-as-we-think-3b3551c440b1
https: //stackoverflow.com/questions/48699573/correct-use-of-arrow-functions-in-react
https: //stackoverflow.com/questions/52571478/how-to-pass-info-from-a-child-component-to-a-function-in-the-parent-component/52571638#52571638
js: Javascript functions always allow for
optional parameters
So if a function expects 3 params, but you send in just one, it run with just the first param
const myFunc = (num1, num2, num3) => { console.log(num1) }
myFunc(55)
> 55
js: To spread an array to fill in a function’s parameters, type
myFunc(…myArray)
note: the old way was
myFunc.apply(null, myArray)
js: To assign all the items in an array into variables in one line, type
(similar to tuple unpacking)
let [a,b,c] = [1,2,3]
note: Must declare all of the items, cannot have unequal arrays.
react: Calling setState({num:4}) and then immediately this.state.num might return your previous this.state.num value because
setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value. There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains.
If you want a function to be executed after the state change occurs, pass it in as a callback.
this.setState({value: event.target.value}, function () {
console.log(this.state.value);
});
js: cool pattern
createTarget(key, ms) {
ms = ms || random(500, 2000);
js: learn
how to make functions that take a callback
https://stackoverflow.com/questions/2190850/create-a-custom-callback-in-javascript
and learn how to set default values in a function when params are not sent in.