Skip to content

Instantly share code, notes, and snippets.

@gilbert
Created February 12, 2018 13:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gilbert/089301f57b7425b195bded6b43b63096 to your computer and use it in GitHub Desktop.
Save gilbert/089301f57b7425b195bded6b43b63096 to your computer and use it in GitHub Desktop.
JSX Formatting Tips
class Showcase extends React.Component {
constructor(props) {
super(props)
this.state = { ... }
}
toggle() {
this.setState({ open: ! this.state.open })
}
render() {
var {open, loading} = this.state
var {client} = this.props
if ( loading ) {
// className is SO ANNOYING but that's React's fault not JSX
return <div className="loading"></div>
}
// Lose parethesis, gain one fewer indentation level.
return <div className="abc">
<h1>Hello</h1>
<div className="text-large padding-2">
{client.name
? <b>Client: {client.name}</b>
: <b>An <i>anonymous</i> client</b>
}
</div>
<p>This client is requesting certain things.</p>
{/* Flatten out your views. Like you would with mithril, but different. */}
{open
? openView.call(this)
: <button onClick={() => this.toggle()}>View Details</button>
}
{/* next.js specific, this is scoped to this component */}
<style jsx>{`
h1 { margin-top: 0; }
`}</style>
</div>
}
}
function openView () {
var {value, items} = this.state
return <div>
{/* With no items you can hide this using css... ul:empty { display: none; } */}
<ul>
{items.map( item =>
<li>Item: {item.name}</li>
)}
</ul>
{items.length === 0 &&
<div className="notice">There are no items.</div>
}
<label htmlFor="in-phone">Phone Number:</label>
{/* Indent elements with many or long properties like this */}
<input
value={value}
onChange={e => {
var val = formatPhoneOrWhatever(e.target.value)
this.setState({ value: val })
}}
id="in-phone"
className="form-input rounded and-stuff"
/>
{/* Works for elems with children too */}
<button
onClick={() => this.toggle()}
className="btn btn-primary btn-rounded btn-plus btn-catastrophe"
>
Close
</button>
</div>
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment