Created
May 28, 2018 19:06
-
-
Save JackHowa/c6aa2b5708e086cbd81080c9f675cadb to your computer and use it in GitHub Desktop.
react fcc beta code snippets
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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> | |
); | |
} | |
} | |
}; |
- 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 />);
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://learn.freecodecamp.org/front-end-libraries/react/give-sibling-elements-a-unique-key-attribute
return
when not a one-liner