react-live
react-live copied to clipboard
Format code with prettier
When modifying code on the fly, it would be very useful to have prettier format the code.
I'd be happy to solve my own problem if someone can guide on how to use prettier on the browser.
This is the problem:

Seems that overflow is giving you trouble?
Try setting “white-space: pre-wrap;” or use “overflow-x: scroll”
That would made it wrap at awkward places.
prettier does a pretty good job at this.
Here's the output with prettier 😍

@siddharthkp itd be great to have as an opt-in feature 😬 I’m sure not everyone will need it. But I wanted to look into Babel-standalone / custom transpilers anyway, so this would fit right in
Good point.
I have no idea what that would look like to be able to help 🙁
If you point me in the right direction, I can give it a shot (after finishing my styleguide)
sorry for the unrelated question, but I was curious how are you injecting the props like that?
@tgreen7 here's the bad code if you want to read through: https://github.com/auth0/cosmos/blob/master/src/docs/spec/playground.js
Hey @siddharthkp ! Have you an example of prettier integration with react-live ? Thanks
@Flo-Slv Here's some hacky code to make it happen:
@siddharthkp thanks! but doesn't work, i've got this error that i don't understand.
Error: TypeError: parseFunction is not a function
I have see discussions on prettier repos to integrate prettier on browser.
If anyone stumbles across this thread, here is how i integrated it with CTRL + L as a hotkey to format:
import prettier from 'prettier/standalone'
import babelParser from 'prettier/parser-babylon'
Then inside your wrapper component:
...
const [code, setCode] = useState(")
const formatOnKey = (e: KeyboardEvent) => {
if (e.ctrlKey && e.keyCode == 76) {
setCode(currentCode =>
prettier.format(currentCode, {
parser: 'babel',
plugins: [babelParser]
}))
}
}
useEffect(() => {
document.addEventListener('keyup', formatOnKey, false)
return () => document.removeEventListener('keyup', formatOnKey, false)
})
...
if you want to do it with a button or something, just use setCode(currentCode => part as your click handler
works on "prettier": "2.0.5"
Thanks @masterpavan ! For me the following worked:
import prettier from 'prettier/standalone';
import babelParser from 'prettier/parser-babel';
...
const formattedCode = prettier.format(unformattedCode, {
parser: 'babel',
plugins: [babelParser],
});
...
<LiveProvider code={formattedCode}
for applying prettier by default.
Works with "prettier": "2.6.1",