How do I configure Prettier format usable React code? - javascript

So I started learning React from this (https://youtu.be/Dorf8i6lCuk?t=1946) tutorial and got stuck trying to save a file. The video recommends getting prettier and I did and then when I save the file it auto-formats code into something that doesn't work.
eg:
as per the suggestion a jsx file:
as per suggestion 2: already in Javascript React:
As per the suggestion in the solutions:

Try going to settings > Extensions > uncheck - Enable/disable checkbox. Or Remove all together.
Change code to: (Notice the differences in my code to yours, your div tags are open and return does not have the divs wrapped in ().
function App() {
return (
<div>
Hello!
</div> //this was giving you the error before
)
}
export default App
I'd also double check your version of react that you are running.
If the version is different from the Tutorials, this could cause issues.
This might help:
Prettier's format on save messes up .jsx files

Following #AlexB801 's advice I have fixed the thing. It turns out you must NOT change the extension to .jsx but only change the formatter. Attaching an image. Also another thing to be noted here is that this was not an issue with Prettier. like so:

Related

How to get auto-suggestion when we style a components inside react.js file?

When we style elements using the app.css or styles.css, vs code simply auto suggest us. example if we type just "back" for background colour, it auto suggest us to complete. but in react.js or index.js it won't work. Why? is there any idea or solution for this? An extension or something. Please excuse my poor english.
solution for this auto-suggestion/auto-complete of this.
In vs code the suggestions are based on the file extension. Therefore, in a js file the vs code only expect JavaScript and it gives suggestions on that. You can use commonly available react extension like ES7+ React/Redux/React-Native snippets
for getting react snippets, component name autocomplete.

Visual Studio code error while saving react files?

And when i am saving this file with Ctrl+s even using prettier and other javascript extension snippets in visual code i am getting this deformed code which is showing errors
And Showing error as:
JSX element div has no corresponding closing tag.
JSX element Navbar has no corresponding closing tag.
JSX element NavbarBrand has no corresponding closing tag.
Identifier expected.
> expected.
The problem is you've installed Beautify as well as Prettify both in your Vscode. Beautify is causing this problem. I tried removing beautify and it worked like a charm. Just remove beautify and use prettify and it will work absolutely well.
Change your file extension to .jsx so the formatter knows that it contains markup
Click 'javascript' in the bottom - right
Then it will come a search bar.
In there you need to search react
Then select the first search result.
DONE
Another variant: change your settings to:
P.S: Change language to JSX in Visual Studio Code
{
"files.associations": {
"*.js": "javascriptreact"
}
}
That way you can either keep your extension as .js
change language mode to javascript react [the language mode should be javascript react as circled] https://i.stack.imgur.com/DDQUH.jpg
You may have installed a formatter that not suit for html+js code snippets.
uninstall (not work whether disable) it and set the default formatter in vs code.
The way I learned to do it is:
The problem is probably that you are using a .js file but intend for it to run React.
Now naturally, Vs code would identify this by itself if you saved it as a .jsx, but you don't want that.
Simply click on the bottom right on VS Code Editor where it says Javascript.
You will see an option to Select the language Mode, here you can search for JavaScriptReact and select. That's it. This should solve your problem.
1 Disable all extension
2 And select the language mode is JavaScriptReact
[see pic is here ]
[1]: https://i.stack.imgur.com/uOwiT.png
type the following commands before creating a new app:
npm install -g create-react-app
npx create-react-app myapp
cd myapp
npm start

Vuejs Error: The client-side rendered virtual DOM tree is not matching server-rendered

I am using Nuxt.js / Vuejs for my app, and I keep facing this error in different places:
The client-side rendered virtual DOM tree is not matching server-rendered content.
This is likely caused by incorrect HTML markup, for example nesting block-level elements inside <p>, or missing <tbody>.
Bailing hydration and performing full client-side render.
I would like to understand what is the best way to debug this error? Is their a way I can record/get the virtual DOM tree for client and server so I could compare and find where the error lies?
Mine is a large application and manually verifying is difficult.
Partial answer: with Chrome DevTools, you can localize the issue and see exactly what element caused the issue. Do the following (I did that with Nuxt 5.6.0 and Chrome 64.0.3282.186)
Show DevTools in Chrome (F12)
Load the page that causes "the client-side rendered virtual DOM tree..." warning.
Scroll to the warning in DevTools console.
Click at the source location hyperlink of the warning (in my case it was vue.runtime.esm.js:574).
Set a breakpoint there (left-clicking at line number in the source code browser).
Make the same warning to appear again. I'm not saying it is always possible, but in my case I simply reloaded the page. If there are many warnings, you can check the message by moving a mouse over msg variable.
When you found your message and stopped on a breakpoint, look at the call stack. Click one frame down to call to "patch" to open its source. Hover mouse over hydrate function call 4 lines above the execution line in patch. Hyperlink to the source of hydrate would open.
In the hydrate function, move about 15 lines from the start and set a breakpoint where false is returned after assertNodeMatch returned false. Set the breakpoint there and remove all other breakpoints.
Make the same warning to happen again. Now, when breakpoint is hit, execution should stop in the hydrate function. Switch to DevTools console and evaluate elm and then vnode. Here elm seem to be a server-rendered DOM element while vnode is a virtual DOM node. Elm is printed as HTML so you can figure out where the error happened.
For me this error happened cuz get Array list in AsyncData and rendered <tr> tags by v-for, i put v-for codes in <client-only> blocks and problem solved
This error can be really painfull to debug. In order to quickly get the element causing an issue edit node_modules/vue/dist/vue.esm.js and add the following lines :
// Search for this line:
function hydrate (elm, vnode, insertedVnodeQueue, inVPre) {
var i;
var tag = vnode.tag;
var data = vnode.data;
var children = vnode.children;
inVPre = inVPre || (data && data.pre);
vnode.elm = elm;
// Add the following lines:
console.log('elm', elm)
console.log('vnode', vnode)
console.log('inVpre', inVPre)
// ...
You will get in the console the failing node.
There are a lot of ways of fixing this issue, but most of them are not actual fixes, just hacky band-aids. To note a few:
wrap it into <client-only> tags, beware of some important details tho
using a v-show instead of a v-if
trying to hack some lifecycles
etc...
I highly recommend reading this gorgeous article written by Alexander Lichter
https://blog.lichter.io/posts/vue-hydration-error/
He'll explain you that you should diagnose why this happens and fix the actual issue.
Basically each time something is different from what was generated on the server and what is available when done hydrating on the client will cause this error.
Some of which are:
invalid HTML (having a block element inside of a <p>, same goes for an a tag nested into another, etc...)
3rd party scripts messing around with your components
different state on server vs client
any random is risky (new Date() for example)
any page related to authentication
I highly recommend reading the article to understand in Alexandre's own words how to handle this kind of issue. If you're in a hurry you could always use one band-aid fix but try to actually fix the issue for the best performance and to keep the code clean.
I had the same issue as of nuxt version 2.14.0 while implementing vue-particles package. The fix was to surround the tags with no-ssr and it fixed the issue.
EDIT:
Updated variant of the solution (if Nuxt version is above 2.9.0)
<client-only>
<vue-particles>
</vue-particles>
</client-only>
Old solution:
<no-ssr>
<vue-particles>
</vue-particles>
</no-ssr>
Thanks to budden73's answer, I did a little improvement on the debug process.
Open dev tool
click on the warn message, and click on the first line of the warn message, you will be directed to the Sources panel, with a file name vue.runtime.esm.js?xxxx
ctrl+f to search the above file for assertNodeMatch, not the function, but like:
if (process.env.NODE_ENV !== 'production') {
if (!assertNodeMatch(elm, vnode, inVPre)) {
return false
}
}
Add a break point at the line return false
Refresh the page, and the breakpoint will be triggered.
At the right side of the Sources panel, Under Scope->Local, click on the elm element, you will be directed back to the Elements panel.
The above element is the client side rendered element, compare with your code to see the difference.
If you can't find the source of the bug, the brutal way to fix it is using nuxt's <client-only> tag.
Another likely brutal way is described here. Add an isHydrate variable which default is false, set to true in mounted hook, and render the element after the variable set to true.
For Nuxt version above 2.10 it doesn't need to install nothing, just use the default component <client-only> as mentioned https://nuxtjs.org/api/components-client-only/.
Check the previous warning:
In "nuxt": "^2.12.2", You can spot the cause easily from the previous warning.
In my case:
Incorrect
<nuxt-link to="/game42day">
<a>Game For Today</a>
</nuxt-link>
Correct:
<nuxt-link to="/game42day">
Game For Today
</nuxt-link>
If you're rendering a component conditionally with v-if, then you have two options to solve the problem:
The first one is wrapping the element in <no-ssr></no-ssr> tag.
The second approach is replacing v-if with v-show, here is the link to Vue docs.
Turns out, in my case, I had HTML comment tags , which was causing this stupid, annoying error. Took me too long to figure it out but in case it helps someone.
In my case I had to change this:
<v-expansion-panel-header v-text="name" />
to this:
<v-expansion-panel-header>{{ name }}</v-expansion-panel-header>
I also get many errors due to this problem. I list two cases I often encounter, hope can help you.
With vuetify button, when you create a common component, you should use: <v-btn>{{text}}</v-btn>. Example:
<template>
<v-btn
:width="width"
:color="color"
:class="[rounded ? 'rounded-pill' : 'rounded-lg',textColor]"
v-on:click="onClick"
elevation="0"
:outlined="outlined"
:type="type"
:name="name"
:form="form"
:disabled="disabled"
v-bind="$attrs"
>{{ text }}</v-btn>
</template>
Don't use v-html with <p> tag.
Not use: <p v-html='html'></p>.
Use: <div v-html='html'></div>.
Besides, if you use <client-only></client-only>, this problem is definitely solved, but if you need to SEO page or show google ads, it is not good solution.
Ok this is going to sound silly. I tried a bunch of different solutions for about 15 mins such as restarting the server and deleting the .nuxt directory but I was too lazy to use #budden73's big brain solution. What ended up working for me was simply restarting my computer, give it a shot.
What I have found so far from observation is that when you are using third party packages like jQuery (specially), they sometimes inject html tags into the dom. So Vue/Nuxt looses track of the dom tree and starts complaining.
I was having the same problem and after a while I removed all jQuery and replaced jQuery functionality with Vuejs and those error were all gone.
See here for an example of how to deal with integrations (e.g. Google Analytics or FB Pixel) that modify the DOM. Basically create a plugin and exclude from SSR.
https://nuxtjs.org/faq/ga
What about:
extend (config, ctx) {
config.resolve.symlinks = false
}
See this [Vue warn]: The client-side rendered virtual DOM tree is not matching server-rendered content ( Nuxt / Vue / lerna monorepo )
Now that you found the code causing the problem, the first thing you should do is to verify that your markup (possibly coming from an API) is valid. Code like <p><p>Text</p></p> is not valid because a p element doesn’t allow other block elements (like a paragraph tag) inside.
Be aware, that tags are not allowed to have block level elements like <div> or <p> as children. These <span> tags are used default tag for Vue’s transitions though. You can change that though via <Transition tag="div">.
Check if have used any block-level element inside the inline element.
for example: inside , inside
If you have used an HTML table make sure you have used the tag
In my case, I changed my codes from
<p v-html="$md.render(post.content)"></p>
to
<p>{{ $md.render(post.content) }}</p>
In my case this problem was caused by markdownit module, I solved it by changing the html markup used with v-html. I was with <p> at the beginning and I ended with <div>.
I have some <p> in my v-html render (with $md.render()) so take care if you have same problems with different markups.

after vscode format code the program doesn't work [duplicate]

I've the following snippet in my index.js
class App extends Component {
render() {
return ( <div style = { styles.app } >
Welcome to React!
</div>
)
}
}
The code works, but every time I save (ctrl+s) visual studio format the jsx like that:
class App extends Component {
render() {
return ( < div style = { styles.app } >
Welcome to React!
<
/div>
)
}
}
How can I solve this? thanks
In the end what did the trick was changing the file format from JavaScript to JavaScript React on the bottom toolbar.
I'm publishing it here for future reference since I didn't find any documentation on this topic.
In addition to the above. If you click 'Configure File Association for .js' you can set all .js files to Javascript React
change vscode preferences settings > user settings below:
"files.associations": {
"*.js":"javascriptreact"
}
You can prevent VSC from incorrectly formatting your JSX by adding an association in your settings.json
Code > Preferences > Settings
In the settings window search for associations, click edit in settings.json and then add:
"files.associations": {
"*.js": "javascriptreact"
}
Alternatively, saving the file with a .jsx extension resolves this in vscode.
I had the same challenge and I am hoping to discover a better way of handling this issue in vscode.
I noticed your suggested work-around has to be done each time you open the react file with an extension of .js
Open the Visual Studio Code Settings. Refer the image below to see how to navigate to the settings.
Once the settings tab is open. If you want to make the settings changes for all the projects then select the User sub tab, if only for current project then select the Workspace sub tab.
type "file associations" in the search text box and press Enter.
Click on add item.
set Item : *.js
set Value : javascriptreact
Above changes will start associating all *js files in the project as javascript React files.
Next open any .js file in your project and right click and select Format Document. If you have multiple formatters then associate your favorite formatter. I have used Prettier to handle my formatting.
Install Prettier (if not installed by default) and try to add this to your user or workplace settings:
"prettier.jsxBracketSameLine": true
Do not put linebreak between return and the returned JSX expression.
Trigger autoformat (Alt+Shift+F) and check if works.
I struggled with this but finally found a solution. This is my settings.json
{
"terminal.integrated.shell.windows": "C:\\Program Files\\Git\\bin\\bash.exe",
"workbench.startupEditor": "welcomePage",
"window.zoomLevel": 1,
"emmet.includeLanguages": {
"javascript": "javascriptreact",
"vue-html": "html"
},
"editor.formatOnSave": true,
"javascript.updateImportsOnFileMove.enabled": "always",
"editor.wordWrap": "on",
"editor.tabSize": 2,
"editor.minimap.enabled": false,
"workbench.iconTheme": "vscode-icons",
"eslint.autoFixOnSave": true,
"eslint.alwaysShowStatus": true,
"beautify.ignore": [
"**/*.js",
"**/*.jsx"
],
"prettier.jsxSingleQuote": true,
"prettier.singleQuote": true
}
I added
"beautify.ignore": ["**/*.js","**/*.jsx"]
Make sure you dont have multiple javascript formatters enabled in your current workspace. (You have to disable the rest of them for your current workspace).
react-beautify mostly does the magic but fails if you have some other JS formatter/beautifier already installed.
In my case, I had react-beautify and JS-CSS-HTML Formatter extension installed. I had to disable the JS-CSS-HTML Formatter for my current workspace.
Here is what worked for me-
I clicked on the Language mode (Javascript React) at the bottom of the screen
Then chose the Configure React Javascript Language based setting option
Then changed the javascript react default formatter to prettier as shown in the pic.
That pretty much did it for me after I saved the React file.
I just added all the combinations mentioned above.
added this
"files.associations": {
"*.js": "javascriptreact"
}
added this also
"beautify.ignore": ["**/*.js","**/*.jsx"]
Deleted additional js formatting
installed prettier
turn ON prettier and formatting
You can install an extension like react-beautify that helps you format your jsx code.
It is found here
This extension wraps prettydiff/esformatter to format your javascript, JSX, typescript, TSX file.
I had to disable the JS-CSS-HTML Formatter extension in VSC. only solution to this problem
Prettier is an opinionated code formatter. It enforces a consistent style by parsing your code and re-printing it with its own rules that take the maximum line length into account, wrapping code when necessary.
include :
JavaScript
TypeScript
Flow
JSX
JSON
CSS
SCSS
Less
HTML
Vue
Angular
GraphQL
Markdown
YAML
https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode
I had similar problem, then I found out it was caused by 'beautify' extension. After I uninstalled the extension, everything is working fine.
After reading many great suggestions and workarounds, I discovered that I could simply place my mouse arrow down over the bright blue horizontal bar at the bottom of VSCode editor window - right click - which opens a popup list window - and deselected = "Editor Indentation".
You can double click JavaScript in the Status Bar at the bottom of VSCode, and then change the format from JavaScript to React (Choose React in the Select language mode to associate with '.jsx')
add this in your .js code,
/* prettier-ignore */

React/Node - Include js component in another file

I have a component in a .js file which I have exported as default. I am trying to include this component in another .js file. I have also imported this component in the other file. I have tried using <componentName /> but this does not seem to work, it compiles and shows no error but nothing shows up. Any ideas?
First of all, as you are saying you are using it like <componentName />, this won't work, you should try renaming it with all caps ie. <ComponentName />. This is just an assumption. If the issue persists, please share the code, so that we can help you in a better way.
Discussion can be found here.
As mentioned in the comments, the component name that I was attempting to add is required to start with a capital letter as components beginning with lowercase letters are searched as default DOM elements

Categories

Resources