-
-
Save JackHowa/c6aa2b5708e086cbd81080c9f675cadb to your computer and use it in GitHub Desktop.
// React - Bind 'this' to a Class Method | |
class MyComponent extends React.Component { | |
constructor(props) { | |
super(props); | |
this.state = { | |
visibility: false | |
}; | |
// change code below this line | |
this.toggleVisibility = this.toggleVisibility.bind(this) | |
// change code above this line | |
} | |
// change code below this line | |
toggleVisibility() { | |
this.setState({ | |
visibility: !(this.state.visibility) | |
}) | |
} | |
// change code above this line | |
render() { | |
if (this.state.visibility) { | |
return ( | |
<div> | |
<button onClick={this.toggleVisibility}>Click Me</button> | |
<h1>Now you see me!</h1> | |
</div> | |
); | |
} else { | |
return ( | |
<div> | |
<button onClick={this.toggleVisibility}>Click Me</button> | |
</div> | |
); | |
} | |
} | |
}; |
https://learn.freecodecamp.org/front-end-libraries/react/introducing-inline-styles
in-line styles
- Don't use kebab-case (lol) for keys like in css (eg, this-is-css-key: "name")
- Use camel case
- Remember to use {{}} around the in-line style value `<div style={{fontSize: "10px"}} >
- Seems like px can be omitted: "Note that you can optionally set the font size to be a number, omitting the units "px", or write it as "72px"."
class Colorful extends React.Component {
render() {
return (
<div style={{color: "red", fontSize: "72px"}}>Big Red</div>
);
}
};
https://learn.freecodecamp.org/front-end-libraries/react/add-inline-styles-in-react
- set style object outside of the class
- use constant style object to keep code organized -- not inline styles
- px is assumed unless otherwise said
const styles = {color: "purple", fontSize: 40, border: "2px solid purple"};
// change code above this line
class Colorful extends React.Component {
render() {
// change code below this line
return (
<div style={styles}>Style Me!</div>
);
// change code above this line
}
};
- get random index from arr
let rand = myArray[Math.floor(Math.random() * myArray.length)];
- can assign a variable from the random
const inputStyle = {
width: 235,
margin: 5
}
class MagicEightBall extends React.Component {
constructor(props) {
super(props);
this.state = {
userInput: '',
randomIndex: ''
}
this.ask = this.ask.bind(this);
this.handleChange = this.handleChange.bind(this);
}
ask() {
if (this.state.userInput) {
this.setState({
randomIndex: Math.floor(Math.random() * 20),
userInput: ''
});
}
}
handleChange(event) {
this.setState({
userInput: event.target.value
});
}
render() {
const possibleAnswers = [
'It is certain',
'It is decidedly so',
'Without a doubt',
'Yes, definitely',
'You may rely on it',
'As I see it, yes',
'Outlook good',
'Yes',
'Signs point to yes',
'Reply hazy try again',
'Ask again later',
'Better not tell you now',
'Cannot predict now',
'Concentrate and ask again',
'Don\'t count on it',
'My reply is no',
'My sources say no',
'Most likely',
'Outlook not so good',
'Very doubtful'
];
const answer = possibleAnswers[this.state.randomIndex];
return (
<div>
<input
type="text"
value={this.state.userInput}
onChange={this.handleChange}
style={inputStyle} /><br />
<button onClick={this.ask}>
Ask the Magic Eight Ball!
</button><br />
<h3>Answer:</h3>
<p>
{ /* change code below this line */ }
{answer}
{ /* change code above this line */ }
</p>
</div>
);
}
};
random arr value via https://stackoverflow.com/questions/4550505/getting-a-random-value-from-a-javascript-array?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa
fancy way of doing it using short-circuiting hehe
{display &&
<h1>Displayed!</h1>
}
answer: https://learn.freecodecamp.org/front-end-libraries/react/render-with-an-ifelse-condition
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
display: true
}
this.toggleDisplay = this.toggleDisplay.bind(this);
}
toggleDisplay() {
this.setState({
display: !this.state.display
});
}
render() {
// change code below this line
let display;
if (this.state.display) {
display = <h1>Displayed!</h1>;
} else {
display = null;
}
return (
<div>
<button onClick={this.toggleDisplay}>Toggle Display</button>
{display}
</div>
);
}
};
slightly better way of doing it:
use short-circuited && operator and use reference within render method
render() {
// change code below this line
const display = this.state.display;
return (
<div>
<button onClick={this.toggleDisplay}>Toggle Display</button>
{display && <h1>Displayed!</h1>}
</div>
);
}
lol that was the next challenge
https://learn.freecodecamp.org/front-end-libraries/react/use--for-a-more-concise-conditional
- logical && operator that makes it more concise
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
display: true
}
this.toggleDisplay = this.toggleDisplay.bind(this);
}
toggleDisplay() {
this.setState({
display: !this.state.display
});
}
render() {
// change code below this line
return (
<div>
<button onClick={this.toggleDisplay}>Toggle Display</button>
{this.state.display && <h1>Displayed!</h1>}
</div>
);
}
};
remember to initialize state within the this.state = {}
and to use :
not =
for key value pairs
constructor(props) {
super(props);
// change code below this line
this.state = {
input: '',
userAge: ''
}
// change code above this line
this.submit = this.submit.bind(this);
this.handleChange = this.handleChange.bind(this);
}
- use Number() static constructor to make explicit the coercion
- check for existence of it in state
- render the button conditionally
- ternary inside a ternary
const inputStyle = {
width: 235,
margin: 5
}
class CheckUserAge extends React.Component {
constructor(props) {
super(props);
// change code below this line
this.state = {
input: '',
userAge: ''
}
// change code above this line
this.submit = this.submit.bind(this);
this.handleChange = this.handleChange.bind(this);
}
handleChange(e) {
this.setState({
input: e.target.value,
userAge: ''
});
}
submit() {
this.setState({
userAge: this.state.input
});
}
render() {
const buttonOne = <button onClick={this.submit}>Submit</button>;
const buttonTwo = <button>You May Enter</button>;
const buttonThree = <button>You Shall Not Pass</button>;
return (
<div>
<h3>Enter Your Age to Continue</h3>
<input
style={inputStyle}
type="number"
value={this.state.input}
onChange={this.handleChange} /><br />
{
this.state.userAge ?
Number(this.state.userAge) >= 18 ?
buttonTwo :
buttonThree
:
buttonOne
}
</div>
);
}
};
https://learn.freecodecamp.org/front-end-libraries/react/render-conditionally-from-props
- pass in props to then conditionally render child component
- those props can be determined elsewhere
- useful chance calculate
Math.random() > .5
- remember to make comments like
{ /* change code below this line */ }
class Results extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<h1>
{
this.props.fiftyFifty ?
"You win!" :
"You lose!"
}
</h1>
)
};
};
class GameOfChance extends React.Component {
constructor(props) {
super(props);
this.state = {
counter: 1
}
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState({
counter: this.state.counter + 1
});
}
render() {
let expression = Math.random() > .5;
return (
<div>
<button onClick={this.handleClick}>Play Again</button>
{ /* change code below this line */ }
<Results fiftyFifty={expression} />
{ /* change code above this line */ }
<p>{'Turn: ' + this.state.counter}</p>
</div>
);
}
};
- can use basic if/then logic within render()
- can reassign styles within render
class GateKeeper extends React.Component {
constructor(props) {
super(props);
this.state = {
input: ''
};
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
this.setState({ input: event.target.value })
}
render() {
let inputStyle = {
border: '1px solid black'
};
// change code below this line
if (this.state.input.length > 15) {
inputStyle = {
border: '3px solid red'
}
}
// change code above this line
return (
<div>
<h3>Don't Type Too Much:</h3>
<input
type="text"
style={inputStyle}
value={this.state.input}
onChange={this.handleChange} />
</div>
);
}
};
- render the items in an array with a map
- setup list items with jsx
const textAreaStyles = {
width: 235,
margin: 5
};
class MyToDoList extends React.Component {
constructor(props) {
super(props);
// change code below this line
// state object
this.state = {
userInput: '',
toDoList: []
}
// change code above this line
this.handleSubmit = this.handleSubmit.bind(this);
this.handleChange = this.handleChange.bind(this);
}
handleSubmit() {
const itemsArray = this.state.userInput.split(',');
this.setState({
toDoList: itemsArray
});
}
handleChange(e) {
this.setState({
userInput: e.target.value
});
}
render() {
const toDoList = this.state.toDoList;
// will need to eventually use the index for unique key
// the {} evaluates the item
const items = toDoList.map((item, i) => <li>{item}</li>);
return (
<div>
<textarea
onChange={this.handleChange}
value={this.state.userInput}
style={textAreaStyles}
placeholder="Separate Items With Commas" /><br />
<button onClick={this.handleSubmit}>Create List</button>
<h1>My "To Do" List:</h1>
<ul>
{items}
</ul>
</div>
);
}
};
- unique keys required hehe
- have to remember to
return
when not a one-liner
const frontEndFrameworks = [
'React',
'Angular',
'Ember',
'Knockout',
'Backbone',
'Vue'
];
function Frameworks() {
const renderFrameworks = frontEndFrameworks.map((framework, index) => {
return <li key={index}>{framework}</li>
})
return (
<div>
<h1>Popular Front End JavaScript Frameworks</h1>
<ul>
{renderFrameworks}
</ul>
</div>
);
};
- intersestingly, you can get a decodeable error message to open
- when looping through the objects, remember to specify its property -- not just itself
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
users: [
{
username: 'Jeff',
online: true
},
{
username: 'Alan',
online: false
},
{
username: 'Mary',
online: true
},
{
username: 'Jim',
online: false
},
{
username: 'Sara',
online: true
},
{
username: 'Laura',
online: true
}
]
}
}
render() {
const users = this.state.users;
const usersOnline = users.filter(user => user.online);
const renderOnline = usersOnline.map((user, index) => {
return <li key={index}>{user.username}</li>;
})
return (
<div>
<h1>Current Online Users:</h1>
<ul>
{renderOnline}
</ul>
</div>
);
}
};
- Can render on the server side
- Useful perhaps for performance:
Second, this creates a faster initial page load experience because the rendered HTML is smaller than the JavaScript code of the entire app. React will still be able to recognize your app and manage it after the initial load.
- to reference App, need to use
<App />
class App extends React.Component {
constructor(props) {
super(props);
}
render() {
return <div/>
}
};
// change code below this line
ReactDOMServer.renderToString(<App />);
https://learn.freecodecamp.org/front-end-libraries/react/optimize-re-renders-with-shouldcomponentupdate
x % 2 === 0
nextProps.value
not justnextProps
shouldComponentUpdate()
checks for performance of whether to re-render, returns bool