React-slick Slider stays on same page if slides items are changed - reactjs

I am stuck with an issue with react-slick. The subject line may not make sense, but I will try to explain the scenario in detail. See this example fiddle to see the issue in action.
var DemoSlider = React.createClass({
getSlides(count) {
var slides = [];
for(var i = 0; i < count; i++) {
slides.push((<img key={i} src='http://placekitten.com/g/400/200' />));
}
return slides;
},
render: function() {
var settings = {
dots: false,
infinite: false,
slidesToShow: 3,
slidesToScroll: 3
}
var slides = this.getSlides(this.props.count);
return (
<div className='container'>
<Slider {...settings}>
{ slides }
</Slider>
</div>
);
}
});
In this demo, initially the slider shows 20 slides (3 per page). The idea is that if you click the button, it will generate a random number, which would be the new number of slides. The code is fairly simple and self-explanatory.
To reproduce the problem,
1. keep on clicking Next arrow until you reach the last slide.
2. click on the button that says 'Click' to generate a new random number of slides.
My expectation was that the slide will go back to the first slide but not to stay on the page where it previously was. Even worse, if the new number of slides is lower than the previous number, the user will see a blank page with no slides. On clicking Previous error, he/she can go to the previous slides, and everything works normally but the initial display ruins the user experience.
Is there something I am missing to add in the code, or is this a bug?
Thanks,
Abhi.

I would say it is rather a buggy behavior, but still you can achieve what you want by forcing a redraw after new collection has been passed as props, by resetting react's key:
<DemoSlider key={Date.now()} count={this.state.count}/>
UPDATED FIDDLE

Quick workaround: When you change to a new set of slides, remove the component, and reconstruct it again. It would then start with the first slide. You can do this by incrementing the key attribute of DemoSlider.
For a proper fix, you'd need to tell the component to change the 'current slide', so that it's not looking at a slide index beyond the end, but a casual look at the source at https://cdnjs.cloudflare.com/ajax/libs/react-slick/0.11.0/react-slick.js suggests it currently does not allow this. A change would need to be made to InnerSlider.componentWillReceiveProps() to check state.currentSlide against props.slidesToShow and state.slideCount.
It would also benefit from allowing currentSlide to be passed as props.

Related

Limit the number of results for autocomplete component?

I'm using React JS and I've created an autocomplete component that returns a list of results.
Here's my code for the autocomplete :
const [pokedexMatch, setPokedexMatch] = useState([]);
const searchPokedex = (text) => {
if (!text) {
setPokedexMatch([]);
} else {
let matches = pokedex.filter((pokedex) => {
const regex = new RegExp(`${text}`, "gi");
return pokedex?.name?.match(regex);
});
setPokedexMatch(matches);
}
};
Here's a working sandbox with some dummy text below. As you can see, when you type a single letter it returns a lot of results and move the text below the results.
What I'd like to do is limit the number of results to 5 and make the list of results go above the text (I guess that I should use absolute positioning but I'd like to know if there is another method without absolute positioning) ?
To limit your results to 5, use simple Javascript!
setPokedexMatch(matches.slice(0, 5));
For the positioning part of your question, you're on the right track - you can use absolute positioning of a div with a white background to make the results appear to be "above" the text.
EDIT: I've updated your sandbox here and made some very minor changes.
When you map over an array, make sure you include a key prop. Read more here.
I added the slice method to limit your results to 5
I added a simple above class to the parent <ul /> element to make the results appear "above" the text. This is just one way to accomplish this, I'll leave it to you to style it better if you'd like.

AngularJS - div still shows even without condition

Ok, I know that title could use some work, but I'm not sure how else to put it.
Here's the setup.
I have a (potentially) massive table that gets generated via an ng-repeat. All the rows need to be editable but, when the dataset is so large, all those bindings slow things to a crawl. I could literally be waiting upwards of 20 seconds for large sets to load!
We noticed that dumping the data in a read-only state significantly decreased the load time. So, we came up with the idea of loading it read-only, but, when the table row was clicked, it became editable. This is accomplished like so. I have two cells output. editableRow is initially false. When the row is clicked, editableRow becomes true. The idea being that, when editableRow becomes true, I see the other cell.
(proprietary code obfuscated)
<TABLE-CELL class="value-col" ng-if="readtime.editableRow === true">
<input type="text"
name="readingTime"
ng-model="<data model>"
ng-disabled="<param>"
ng-change="<function>"
ng-class="<classes>"
/>
</TABLE-CELL>
<TABLE-CELL class="value-col" ng-if="readtime.editableRow === false">
<input type="text"
placeholder="{{<data model>}}"
ng-class="<classes>"
/>
</TABLE-CELL>
The problem is, on the click, for a tiny fraction of a second both cells are visible. It really is only visible on the first click. Subsequent clicks still do it, but it goes so fast that the human eye can't catch it. I know it's there since I slowed everything down with a breakpoint on the mouse click. This also revealed that this happens as the value turns true - turning on the first cell, but the second one doesn't disappear in the same moment. So, it causes a "flicker" of sorts. This seems to happen outside my actual code, inside the jQuery, so I'm not sure how to short circuit it.
I've tried playing with using ng-show/hide instead, which worked a little bit, but also totally negated the time-saving aspect, since it actually renders everything, and it took a long time. I've also tried ng-cloak with no effect whatsoever.
The breakpoint that it keeps stopping on (when I told it to stop on event listeners to do with the mouse click) is the following code in jquery.js:
if ( !(eventHandle = elemData.handle) ) {
eventHandle = elemData.handle = function( e ) {
// Discard the second event of a jQuery.event.trigger() and
// when an event is called after a page has unloaded
return typeof jQuery !== strundefined && jQuery.event.triggered !== e.type ?
jQuery.event.dispatch.apply( elem, arguments ) : undefined;
};
}
It hits that line about 4 times, and, on the last one, both cells are visible. Then, the second one disappears.
I'm out of ideas and would appreciate any thoughts on this.
I finally found an answer that works!
On this page: disable nganimate for some elements the answer right BELOW the accepted answer is what finally worked!
To disable ng-animate for certain elements, using a CSS class, which follows Angular animate paradigm, you can configure ng-animate to test the class using regex.
Config
var myApp = angular.module("MyApp", ["ngAnimate"]);
myApp.config(function($animateProvider) {
$animateProvider.classNameFilter(/^(?:(?!ng-animate-disabled).)*$/);
})
Usage
Simply add the ng-animate-disabled class to any elements you want to be ignored by ng-animate.

react-highcharts how to call reflow?

I use kirjs/react-highcharts plugin for react but I have no idea how to get Highchart component in order to call reflow like: $('#container1').highcharts().reflow()
From docs its tells:
For access to methods & properties from the Highcharts library you can use ReactHighcharts.Highcharts. For example, the Highcharts options are available via ReactHighcharts.Highcharts.getOptions().
but I don't see there any reflow() method.
Any ideas?
Edit
its located under ReactHighcharts.Highcharts.charts so I can call
ReactHighcharts.Highcharts.charts[0].reflow()
but it has list of all highchart instances so I have no information what index is mine
I am using highcharts-react-official and highcharts. They are available via npm . Although I am using different packages, the working principle should be the same.
The way of using reflow() function in react-highchart is also Highcharts.charts[i].reflow(). I have prepared 2 code sandboxes for the demonstration. The first code sandbox shows the way of re-flowing every chart, and the second code sandbox shows the way of re-flowing a particular chart.
The first code sandbox link is here.
There is a button on App.js to hide and show highchart divs.
The child component is React.memo (for performance optimization), therefore the hidden highchart will not be auto resized after it becomes visible.
To let every chart window resize with respect to the window size. The following code is placed in App.js. It looks for all existing charts and re-flow them:
for (var i = 0; i < Highcharts.charts.length; i++) {
if (Highcharts.charts[i] !== undefined) {
Highcharts.charts[i].reflow();
}
}
The second code sandbox link is here.
Almost the same as the first code sandbox, but there is a ref array of referencing every chart.
The chart which needs re-flowing is placed with an id in its chart option.
Iterate every chart and get the index of the chart with that id e.g. "secondChart" for this example.
for (var i = 0; i < chartRef.current.length; i++) {
if (
chartRef.current[i].chart.userOptions.id !== undefined &&
chartRef.current[i].chart.userOptions.id === "secondChart"
)
Highcharts.charts[chartRef.current[i].chart.index].reflow();
}
Re-flow that chart.
The Reflow can be set with event load in options.
Workaround: You have to set reflow() using setTimeout() this will trigger the resizing. Time is set to 0 to avoid delay.
Solution
const options = {
chart: {
type: 'column',
style: {},
events: {
load() {
setTimeout(this.reflow.bind(this), 0);
},
},
},
title: 'Column Chart',
}
Usage
<HighchartsReact highcharts={Highcharts} options={options} />

Onsen-UI Swipe Navigation [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I'm trying to figure out how to implement the "android" feel on Onsen-UI by using the 'swipe' navigation.
I tried implementing idangerous swiper, but not having much luck. My idea is to combine:
http://codepen.io/negibouze/pen/jEvOYz
enter code here
http://codepen.io/negibouze/pen/wBLeyp
enter code here
When you swipe, the tabs change but has that swipe animation/effect. I also would love it if each tab/swipe was a different html and not one index file.
Any ideas or help?
Great question. There are two different approaches:
As it's done in your second example, using tabbar and gesture detector. Onsen 2.0 has a slide animation for tabbar, so you just need to add <ons-tabbar animation="slide" ... >. Onsen 2.0 is still in alpha version but it will be released in the upcoming weeks. The drawback of this approach is that the slide animation starts after the swipe action is completed.
You basically add your ons-tabbar element and then configure the gesture detector as follows:
ons.ready(function() {
// Create a GestureDetector instance over your tabbar
// The argument is the actual HTMLElement of tabbar, you can also do document.getElementById(...)
var gd = ons.GestureDetector(myTabbar._element[0]);
gd.on('swipe', function(event) {
var index = myTabbar.getActiveTabIndex();
if (event.gesture.direction === 'left') {
if (index < 3) {
myTabbar.setActiveTab(++index);
}
} else if (event.gesture.direction === 'right') {
if (index > 0) {
myTabbar.setActiveTab(--index);
}
}
})
});
Working here: https://jsfiddle.net/frankdiox/o25novtu/1/
Combining ons-tabbar and ons-carousel elements. The drawback of this approach is that ons-carousel-item cannot get a template or separated file (check the comments to find another workaround to this).
ons-tab requires a page attribute and you cannot leave it blank without errors in the console, but we can use ons-tabbar's style instead of the actual component: http://onsen.io/reference/css.html#tab-bar
We combine it now with a fullscreen carousel like the one you mentioned and add the next CSS to make the page content respect our tabbar so it does not fall over or behind it:
ons-carousel[fullscreen] {
bottom: 44px;
}
Next step, we link every tab with its corresponding carousel item:
<div class="tab-bar" id="myTabbar">
<label class="tab-bar__item" onclick="carousel.setActiveCarouselItemIndex(0)">
...
</label>
<label class="tab-bar__item" onclick="carousel.setActiveCarouselItemIndex(1)">
...
</label>
<label class="tab-bar__item" onclick="carousel.setActiveCarouselItemIndex(2)">
...
</div>
And so on. This will make that when we click on a tab the carousel changes automatically. Now we need to do the opposite connection: update the checked tab when we swipe the carousel. The tabbar is basically a set of radio buttons, so we just need to get the one we want in the carousel's postchange event and check it:
ons.ready(function(){
carousel.on('postchange', function(event){
document.getElementById('myTabbar').children[event.activeIndex].children[0].checked = true;
});
});
You can now change the content of every carousel-item-index and insert an ons-page with anything you want.
Working here: http://codepen.io/frankdiox/pen/EVpNVg
We may add a feature to make this easier in upcoming versions of OnsenUI.
Hope it helps!

How to remove draggability from an element with Ext JS?

I have a div that I want to make draggable or not, depending on the state of some other stuff on my page. I seem to be able to easily make it draggable, but I can't seem to figure out how to best remove the draggability from the div.
I am making it draggable with:
var dd = Ext.create('Ext.dd.DDProxy', mydiv, 'myDDGroup', { isTarget: false });
And I've tried to then remove the draggability by removing the only group it's a member of
dd.removeFromGroup('myDDGroup');
and just destroying the dd object with
delete dd;
Neither of these seem to actually keep me from starting a drag on the element. I suspect I should be able to use the b4Drag override in some way to simply cancel a drag of my div before it even begins, rather than toggling the draggable state of the div at all, but I can't seem to find docs on how I might cancel the drag during the b4Drag call.
So, how can I make a div undraggable after I have already made it draggable?
Seems to be working for me.
Here is the JSFiddle http://jsfiddle.net/01gx33h0/
var dd = Ext.create('Ext.dd.DDProxy', 'test123', 'myDDGroup', { isTarget: false });
Ext.fly('btn123').on('click', function() {
dd.removeFromGroup('myDDGroup');
});
Can you give me the sample code where it is not working. And what version of ExtJs are using?
You have to unreg. Not removeFromGroup.
It just removes from group. But events are not removed on that element.
dd.unreg();
https://fiddle.sencha.com/#fiddle/1eun
When looking at something specific that needs to be dragged, you might consider that allowing dragging is something users expect, for general ease of use you might try the ondragstart="return, this could be appended to your images, or links like so:
<a ondragstart="return false" href="#link">link</a>.

Resources