Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
React components
const MyBetterDiv = props => (
<div className="better" {...props} />
)
<div class="better" data-gorrion="gorrion" data-other="other prop">Gorrion is always bettter</div>
<MyBetterDiv data-gorrion="gorrion" data-other="other prop">Gorrion is always bettter</MyBetterDiv>
const Button = (props) =>
<button onClick={props.onClick}>{props.buttonText}</button>
class ButtonIncrement extends React.Component {
constructor(props) {
super(props)
this.state = { counter: 0 }
}
handleOnClick = () => {
this.setState((prevState) => ({
counter: prevState.counter + 1
}));
}
render() {
return (
<Button
onClick={this.handleOnClick}
buttonText={`Current counter: ${this.state.counter}`}
/>
)
}
}
const Commentlist = ({comments}) => (
<ul>
{comments.map(({ body, author }) =>
<li>{body}-{author}</li>
)}
</ul>
)
class CommentListContainer extends React.Component {
constructor() {
super();
this.state = { comments: [] }
}
componentDidMount() {
getAsync("https://imaginary-api.gorrion.io/my-comments")
.then(comments => this.setState({ comments }))
}
render() {
return <CommentList comments={this.state.comments} />;
}
}
const Connect = ComposedComponent =>
class extends React.Component {
constructor() {
super()
this.state = { name: "" }
}
componentDidMount() {
//fetching data is a part of HOC
getAsync('https://imaginary-api.gorrion.io/name')
.then(({ name }) => { this.setState({ name: name }) })
}
render() {
return (
<ComposedComponent
{...this.props}
name={this.state.name}
/>
)
}
}
const Greeting = props => <div>Hello {props.name}!</div>
const Greeting = ({ name, ...props }) => (
<div {...props}>Hi {name}!</div>
)
const Greeting = ({name}) => <div>Hello {name}!</div>
const Greeting = ({ name, ...props }) => {
if (!name) {
return <div>Loading...</div>
}
return <div {...props}>Hi {name}!</div>
}
const Loading = () => <p>Loading...</p>
const Worker = props => <p>{props.message}</p>
class WorkerInfo extends React.Component {
state = { worker: null }
componentDidMount() {
// We can make an ajax call here, for e.g.
setTimeout(() => this.setState({
worker: `Hi, I am ${this.props.name} and I am proud to work for ${this.props.employer}`
}), 2500);
}
render() {
// Render the children with a function using state as the argument
return this.props.children(this.state.worker);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment