How can I specify the structure of a <div> conditionally in JSX? - javascript

I'm trying to create a responsive <div> inside a React return() statement, but every way I turn, my code is errored in VSCode. One example of my numerous efforts to structure this (and the one recommended by chatGPT) is:
<div>
{props.platform === "desktop" ? <div className="displaydiv"> : <div>}
</div>
</div>
In this case, the first <div> is errored by VSCode as having no closing tag.
I'm unsure whether or not this code would actually run, ie whether the problem might just be over-enthusiastic VSCode checking. But even if this is the problem, this is no help to me as these errors will obscure genuine errors in my project.

No, ternary on just the opening tag won't work. You can put it on the required attribute:
<div className={props.platform === "desktop" ? "displaydiv" : ""}>
</div>

Related

React "Each child in the list should have a unique 'key' prop" [duplicate]

This question already has answers here:
Understanding unique keys for array children in React.js
(27 answers)
Closed 2 years ago.
I'm learning React and I am having this issue. I've already looked at several stack posts but so far they are not helping me. The issue is, I am 100% positive that my items have a unique key. They are coming from a database, and the primary key DB value is being used in the "key=" attribute. The only possible way they could not be unique is if React is trying to render the array more than once.
I added a wrapper <div> so I could debug out the values so that I could visually ascertain my ids/keys were unique.
Here is my Project.jsx export. In this case, the Project element is a styled.div, but I have tried just a regular div too.
export default ({ project }) => (
<div key={project.id}>
<!-- DEBUG -->
<span>id: {project.id}; name: {project.name}</span>
<!-- /DEBUG -->
<Project>
<NavLink to={`/projects/${project.id}`}>{`${project.name}`}</NavLink>
</Project>
</div>
)
And it is called from my Projects.jsx, like this (there's more to the template, but this is the relevant bit):
<div className="projects">
<Title />
<div className="card">
{
projectList.map(project => (<Project project={project} />))
}
</div>
</div>
Here is a screenshot of the array projectList:
chrome devtools logging out projectList, you can see that each element has as unique "id" property.
Things I have tried:
using React.fragment https://github.com/facebook/react/issues/15620
moving "key=" to the topmost element (it was there already when Project was the topmost element, but I moved it when I added the debugging out div): (closed the link and can't find it :( )
using key={Math.Random()}, which still produced these errors, but it didn't print the list twice or anything
The site still seems to work fine, the links work and everything, it's just a big ugly error in the console (and since this is for a resume, I really don't want any of that!!).
Can someone please help?
you need to provide a key at the highest level in your map, which is your Project component
<div className="projects">
<Title />
<div className="card">
{
projectList.map(project => (<Project project={project} key={project.id}/>))
}
</div>
</div>

React DOMException: Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node

If state is true to play youtube video, and it is false I would like to delete youtube playing.
MY code is as follows.
{this.state.isPreViewVideo && <PlayYouTube video_id="ScSn235gQx0" />}
sandbox URL:
https://codesandbox.io/s/xryoz10k6o
Reproduction method:
If 4-digit characters are included in input form, "isPreViewVideo: true" by setState and if it is less than false
It works fine when state is true,
but when state is false, I encounter this error as follows.
DOMException: Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node.
Uncaught DOMException: Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node.
is there a way to avoid or resolve this error?
In playYouTube.tsx line 78 replace <React.Fragment>...</React.Fragment>
with <div>...</div>
Fragments let you group a list of children without adding extra nodes
to the DOM.
This explains the error
Uncaught DOMException: Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node.
More on fragments here https://reactjs.org/docs/fragments.html
This error, Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node, can also be raised if Google Translate is used (or any other plugin that changes the page DOM).
This is detailed in this Github issue: https://github.com/facebook/react/issues/11538
Problem explanation:
When isPreViewVideo is truthy, you have this:
<PlayYouTube video_id="ScSn235gQx0" />
That probably renders to something like this:
<div> <!-- the root element as rendered by PlayYouTube if isPreViewVideo is truthy -->
<embed /> <!-- the video player or whatever PlayYouTube renders -->
</div>
Now if some code removes the player by directly manipulating the DOM and removing the root div, you'll end up with... Well, with nothing.
But in React's virtual DOM, the root div still exists! So when isPreViewVideo goes falsy, React tries to remove it from the real DOM but since it's already gone, the error is thrown.
The solution:
To expand on #henrik123's answer - wrapping PlayYouTube with a div like this...
<div> <!-- the root element rendered if isPreViewVideo is truthy -->
<PlayYouTube video_id="ScSn235gQx0" />
</div>
...causes this to render:
<div> <!-- the root element rendered if isPreViewVideo is truthy -->
<div> <!-- the element as rendered by PlayYouTube -->
<embed /> <!-- the video player or whatever PlayYouTube renders -->
</div>
</div>
Now the same code that removes the player by removing its root div makes it look like this:
<div> <!-- the root element rendered if isPreViewVideo is truthy -->
</div>
Now when isPreViewVideo goes falsy, the root exists both in React's virtual DOM and in the real DOM so there is no problem in removing it. It's children have changed but React doesn't care in this case - it just needs to remove the root.
Note:
Other HTML elements but div may work too.
Note 2:
Wrapping with React.Fragment instead of a div would not work because React.Fragment doesn't add anything to the real DOM. So with this...
<React.Fragment>
<PlayYouTube video_id="ScSn235gQx0" />
</React.Fragment>
...you still end up with this:
<div> <!-- the root element as rendered by PlayYouTube if isPreViewVideo is truthy -->
<embed /> <!-- the video player or whatever PlayYouTube renders -->
</div>
And you have the same issue.
TL;DR solution:
Wrap PlayYouTube with a div.
This error can occur when you use external JS or jQuery plugins. Let me tell about my case.
Issue description
In my React project I have some links on a page, every link opens a modal with some info and a slider with images inside it. Every link has its own set of images inside the slider. But I have the single modal, it is the same for every link.
Data for modal is stored in a state variable and I change its content on every link click (on every modal open):
const initialData = { title: "", intro: "" }; // here is some empty structure of object properties, we need it for the modalResponse initialization
const [modalData, setModalData] = useState(initialData);
// ...
<div id="MyModal">
<div className="title">{modalData.title}</div>
<div className="intro">{modalData.intro}</div>
<div>{modalData.sliderHtml}</div>
</div>
When I open modal using setModalData() I fill modalData with some new data. HTML-code inside modalData.sliderHtml is something like this structure:
<div class="carousel">
<div class="item"><img src="first.jpg" /></div>
<div class="item"><img src="second.jpg" /></div>
<div class="item"><img src="third.jpg" /></div>
</div>
When modal has opened I call some jQuery code for slider initialization:
useEffect(() => {
$('.carousel').initCarousel({
// some options
});
}, [modalData]);
Then user could close the modal and click the next link. The slider must be filled by new set of images. But I get the error: Uncaught DOMException: Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node.
Error reason
The reason of the issue is in a fact that the jQuery plugin changes the structure of html during initialization. It creates some new blocks inside the .carousel parent (arrows to the left/right, dots for navigation, etc.). And it moves all the .item children inside the new .items block! I get such html structure after the plugin initialization:
<div class="carousel">
<div class="dots">...</div>
<div class="arrows">...</div>
<div class="items">
<div class="item"><img src="first.jpg" /></div>
<div class="item"><img src="second.jpg" /></div>
<div class="item"><img src="third.jpg" /></div>
</div>
</div>
When React tries to change the content of modalData.sliderHtml it executes some magic DOM operations for old structure removing. One of this operations is removeChild method, but the old .item elements can't be found inside the parent .carousel because the plugin moved them inside the new .items element. So, we get the error.
Bug fixing
I started to change modalData content back to the initialData structure every time when the modal is closed.
useEffect(() => {
$('#MyModal').on('hidden.bs.modal', function (e) {
setModalData(initialData);
})
}, []);
So, all html structure inside modalData.sliderHtml is filled by the initial empty data again and we don't get an error on the new link click.
SOLVED for bootstrap alert after manually close button
I had exact error when i close the bootstrap alert error message if it's there manually and then submit the form again. what i had done is to wrap up the AlertError component with extra tag around.
import React from "react";
const AlertError = (props) => {
return (
<div> // <---- Added this
<div className="alert alert-custom alert-notice alert-light-danger fade show" role="alert">
<div className="alert-icon"><i className="flaticon-warning"></i></div>
<div className="alert-text">There is an error in the form..!</div>
<div className="alert-close">
<button type="button" className="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true"><i className="ki ki-close"></i></span>
</button>
</div>
</div>
</div> // <---- Added this
);
};
export default AlertError;
I had same problems with a audio tag and I kept this tag within two nested div and now its working
Most probable cause: something modified the DOM after React
The most probable cause of this issue is that something other than React modified the DOM after React rendered to it.
What's causing this DOM mutation?
Depending on the profile of users who are impacted, there might be a few different causes.
Everyone
If all your users are impacted, you, the developer might be the culprit.
The cause is probably that you are using jQuery or doing DOM manipulations outside of React.
Usual users
If usual users are affected, the most probable cause is Google Chrome translate feature (or Microsoft translate on Edge Chromium).
Thankfully there's an easy solution for that: add a <meta> tag in your HTML <head> (Google documentation).
<meta name="google" content="notranslate" />
This should also disable Microsoft Translator on Edge Chromium.
Advanced users
If only advanced users are affected, and they are not using a translation feature on their browser, then it might be a browser extension or some userscript (most likely run by SpiderMonkey) that causes the problem.
More info
Issue on React repo
SolidJS is also affected
Issue on Chromium bug tracker (please star it to help prioritize it)
This is a very annoying bug to fix. But you should wrap the component that you are rendering it conditionally with span element.
Check this GitHub issue: https://github.com/facebook/react/issues/11538#issuecomment-390386520
In one place of our code was something like this:
render() {
if (el) return <div />
return '';
}
After replacing ' ' with null, all works without errors.
I had the same issue with react. The problem was caused by a google-auth script tag in index.html.
<script src="https://accounts.google.com/gsi/client" async defer></script>
This is while I had another on the JS file causing the issue. Be sure to check for conflicting or repeated CDNs.
In my case, I just needed to reset the state OR make it to initial data when I needed to render it with new data. It fixed the issue.
Ex:
This issue occurred when I was setting table data upon getting API response in useFetch. Before setting the data to state, I first set it to initial value.
setTableData([]);
setTableData(data.response);
I hope it may help someone.
Node.removeChild() - Web APIs | MDN
Uncaught DOMException: Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node.
fix:
unmountContainer() {
// macro task
setTimeout(() => {
// refs
if (containerEle) {
// receive removed node
// eslint-disable-next-line no-unused-vars
let removedChild = document
.querySelector('.page__wrapper')
.removeChild(containerEle);
}
});
}

Don't trigger change detection on child components with Angular 4

In the main template for our Angular 4 application, which is sort of the 'root' template. It contains the container elements for the content area of the page and a sidebar off to the side.
Everything is working great except for older browsers (our customers are very large companies that only have older IE's, so we have to support IE10 and IE11) where the app is really unresponsive (in terms of UI updating and css transitions framerate).
One thing I noticed is that even if I rely on change detection that's purely inside the scope of the main app component, it triggers and executes all of the template code for all of the child components (4 times, in fact).
Here's the main part of my template:
<div class="page-content sidenav-open" id="page-content" #pageContent (window:resize)="adjustMainContent()">
<div [class]="'sidenav ' + (isAnimating ? 'isanimating' : '')" [style.width.px]="sidebar.width" [style.marginLeft.px]="sidebar.isVisible ? 0 : -sidebar.width">
<div class="vertical-resize-bar" (mousedown)="dragStart($event)"> </div>
<div class="sidenav-widget search-widget">
<app-navigation>Loading navigation...</app-navigation>
</div>
</div>
<div [class]="'main-content ' + (isAnimating ? 'isanimating' : '')" (transitionend)="isAnimating = false" [style.width.px]="mainContentWidth">
<router-outlet></router-outlet>
</div>
</div>
Again, functionally, it works great (in Chrome and Firefox, etc...), but not older browsers/computers. I just want those variables in my template snippet there to not trigger change detection on the app-navigation component and its children and whatever component gets loaded into router-outlet.
Am I doing anything (or multiple things) obviously wrong here? I should mention that this is our first Angular app.

How to correctly reference 'nested' tag with each={} in riotjs

I'm trying to work in the concept of a loading tag I can wrap other elements to give a consistent loading display when retrieving data async. Consider the following code:
This example relies on browserify (require) but shouldn't make a difference to
the question
<test>
<loading>
<ul>
1. = <li each={ items }>{ title }</li>
or
2. = <li each={ parent.items }>{ title }</li>
or
3. = <li each={ opt.data.items }>{ title }</li>
</ul>
</loading>
<script>
require('riot');
require('./loading.tag');
this.items = [
{ title: 'title 1'},
{ title: 'title 2'}
];
this.on('mount', function () {
riot.mount('loading', /* for 3 = */ {data: this.items});
})
</script>
</test>
As you can see, the tag is <test /> and contains a nested tag <loading /> which wraps the content <test /> displays. Problem is I'm unsure of the correct way to reference the items array (which would in the real world be pulled in via ajax). I tried options 1 & 2 but nothing would display. 3 works (passing the data as opts) but doesn't feel right.
It may have something to do with <yield /> which is how <loading /> is displaying its contents but I don't know why.
<loading>
<div><yield /></div>
</loading>
When I tried your above code 2 got the correct result. I have a few issues with your above code that may be causing you issues.
1) I've never used require inside of a tag. I doubt it works when requiring a tag file. The .tag extension does nothing. It's the type="riot/tag" that signals a script tag is not javascript but a special script that can be used by riot.
2) You've closed the tag </about> instead of </test>. I think your riot tag just won't compile under these circumstances.
3) I don't know what version of riot you're using, but in 2.3.12 if you mount the test tag then any children (in this case your "loadings") will automatically mount provided you have already loaded the .tag file. I think the problem is that you're calling mount on your "loading" tag twice, which may divorce them from their parent.
I think your issue is that the <loading> tag means nothing when <test> is mounted. You then require loading.tag, which then allows loading to be mounted. Try requiring <loading> before you mount test. I made a js fiddle with how I would do it. Hopefully this answers your question.
https://jsfiddle.net/cm09mtc5/

ReactJS creating extra spans in HTML

I have started working on a project and inherited a large amount of ReactJS that I am trying to sort through and better understand. Currently there is a small issue I'm trying to fix in the app I'm working on.
Here is the code for the render:
render: function() {
return (
<div className="finish-content-container">
<div className='finish-instructions'>
<span>
{this.props.finishInfo.startpage.instructions || ""}
</span>
</div>
{
this.props.userData.score && !this.props.finishInfo.finishpage.hideScore ?
<div className="finish-results">
<span>{"Your Score: " + (this.props.userData.score || "")}</span>
</div> : ""
}
{
this.props.finishInfo.finishpage && this.props.finishInfo.finishpage.graph ?
<div className="finish-graph">
<div dangerouslySetInnerHTML={{__html: processStoredGraph(this.props.finishInfo.finishpage.graph, 250, 450)}}></div>
</div> : ""
}
{
this.props.userData.score && this.props.finishInfo.finishpage && this.props.finishInfo.finishpage.feedback ?
<div className='finish-results-feedback'>
{this._getConditionalText(this.props.finishInfo.finishpage.feedback, this.props.userData.score)}
</div> : ""
}
<div className="finish-content" dangerouslySetInnerHTML={{__html: this.props.finishInfo.startpage.content}}></div>
<div className="finish-button">
<span onClick={this.props.onClick} className="btn finish">REPLAY</span>
</div>
</div>
);
},
Here's what is happening: all the logic seems to work fine, but it's creating addition spans in the HTML and those spans are taking up real estate on the page, even when they have no data.
Any thoughts? I can include the HTML output from the page if that's helpful at all.
To answer your question: React inserts spans in the DOM for various reasons, including to wrap floating text nodes (see this answer), white space (see this answer), and (I think) to set placeholders for components that return null from the render method, among other things. If this is causing issues for you, it's probably because you're using CSS that operates on all span elements, or all span elements within the scope of your component. Ditch the CSS, or make it specific to the elements it needs to style, and you should be fine.
In my opinion, React's approach here is in keeping with the intent of the span element, which ought to be a layout no-op if not associated with a specific class.

Categories

Resources