Hey im a bit new to React. I found this slider which I have implemented and it works fine.
https://caferati.me/demo/react-awesome-slider
My only issue now is I would like it to Autoplay but it seems I cant wrap my head around it. As I understand I need to make a function which will do it for me?
My code so far is.
class Slider extends Component {
render() {
return (
<div className="slider">
<AwesomeSlider cssModule={styles} onFirstMount={slider}>
<div data-src={image2}>
<div className="sliderText">
<div>
<h1>Text For first sike</h1>
<NewsletterButton className="clickMe" text={I18n.t('ClickMe')}/>
</div>
</div>
</div>
<div data-src={image4}>
<Fade left duration={2300}>
<img className="sliderImage2" src={image3}/>
</Fade>
<Zoom duration={2000}>
<div className="sliderText2">
<h1> Text For Slide2 </h1>
<p>Slide 2 Paragraph</p>
</div>
</Zoom>
</div>
<div data-src={image4}>
<Zoom duration={2000}>
<div className="sliderText3">
<h1> Slide3 </h1>
<p>Slider 3 paragrah</p>
</div>
</Zoom>
<Fade bottom duration={2300}>
<img className="sliderImage3" src={image1}/>
</Fade>
</div>
</AwesomeSlider>
</div>
);
}
}
export default Slider;
You can give the below approach a try:
Create a timer (as you are looking for an autoplay) which runs for every 2 seconds or so and call a method named setNextImage in it.
In your componentDidUpdate(),
setTimeout(this.setNextImage, 2000);
In your method write some logic to update state.
setNextImage: function() {
// setState method is used to update the state
let index = this.state.currentIndex;
if(index == yourMax_Image_Count)
index == 1
this.setState({ : this.state.currentIndex -1 });
},
I see there is a attribute selected in AwesomeSlider and you can set this.state.currentIndex as its value
Make sure you are handling timeout properly.
You can get next button with jQuery and use click() function like this
$(document).ready(function () {
setInterval(function() {
$(".button_class").click();
}, 10000);
});
componentDidMount() {
const interval = setInterval(this.handleNextSlide, 12500);
this.interval = interval; }
componentWillUnmount() {
if (this.interval != null) {
clearInterval(this.interval);
} }
handleNextSlide = () => {
const { dataSource } = this.props;
const { currentIndex } = this.state;
if(currentIndex == (dataSource && dataSource.length) - 1) {
this.setState({
currentIndex: 0
});
} else {
this.setState({
currentIndex: this.state.currentIndex + 1
});
} }
render() {
const { dataSource } = this.props;
const { currentIndex } = this.state;
return (
<AwesomeSlider
selected={currentIndex}
cssModule={AwsSliderStyles}
>
{dataSource && dataSource.map((value, key) => {
return (
//Do some stuff.
);
})}
</AwesomeSlider>
);
}
try this by importing "withautoplay"
import withAutoplay from 'react-awesome-slider/dist/autoplay'
const AutoplaySlider = withAutoplay(AwesomeSlider)
and use autoplay tag in your component
<AutoplaySlider
play
cancelOnInteraction={false} // should stop playing on user interaction
interval={6000}
>
<div data-src=/path/to/image.png />
<div data-src=/path/to/image.png />
<div data-src=/path/to/image.png />
</AutoplaySlider>
you can follow this link for more details https://www.npmjs.com/package/react-awesome-slider
Related
i have this code that works almost 100%.
function App() {
const [breakLength, setBreakLength] = React.useState(300)
const [sessionLength, setSessionLength] = React.useState(1500)
const [whichTimer, setWhichTimer] = React.useState (true)
const [timerOn, setTimerOn] = React.useState (false)
const [time, setTime] = React.useState (sessionLength)
React.useEffect(()=>{
setTime (sessionLength)},[sessionLength])
React.useEffect(() => {
if(timerOn){
const timerId = setInterval(() => {
setTime((t)=>{
if (t<=0 && whichTimer){
setWhichTimer (!whichTimer)
return breakLength
}
else if (t<=0 && !whichTimer){
setWhichTimer (!whichTimer)
return sessionLength
}
else {
console.log(whichTimer)
return t-1
}
} )
},1000)
return () => clearInterval(timerId)
}
}, [timerOn])
return (
<div id="container">
<div id="break-label">Break Length</div>
<div id="session-label">Session Length</div>
<div id="break-length">{breakLength}</div>
<div id="session-length">{sessionLength}</div>
<div id="timer-label">{whichTimer? "Session" : "Break"}</div>
<div id="time-left">{time}</div>
<button id="start_stop" onClick={()=>setTimerOn(!timerOn)} >Start</button>
</div>
);
}
ReactDOM.render (<App />, document.getElementById ("root"))
The problem is in the second UseEffect.
This is a timer that have a Session Length and a Break Length.
When Session reaches to 0, starts the break.
Until then i have no problem, but when break reaches to 0 it doesn´t change to Session, break start again.
I´ve put a console.log to see if "whichtimer" changes, and it doesn´t. I really don´t understand why.
Thanks for taking the time
function Final_Set(){
return(
<div id="exercise_sets_decider_box">
{
(function(){
console.log(1);
Final_set_page();
})()
}
</div>
);
function App(){
const [mode, Setmode] = useState("0");
if (mode === "0"){
$(document).on('click', "#purple_box_1", function(e){
Setmode("Final");
});
return(
<div id="purple_box_1">
</div>
);
} else if(mode==="Final"){
$(document).on('click', "#purple_box_2", function(e){
Setmode("0");
});
return(
<div>
<Final_Set></Final_Set>
<div id="practice"></div>
<div id="purple_box_2">
</div>
</div>
)
}
}
In brief, Final_set_page function is appending html code in div:#practice, like $("#practice").append('blahblah'). If I go from mode '0' to mode 'Final', Final_set_page() is well working. But if I return to mode '0' and go back to mode 'Final', console.log() is well working but Final_set_page() is not working. I don't know the reason, and I can't find the solution. Please help!
Maybe the problem is in jQuery.
I have rewritten the code. Maybe edit this code instead according to your needs.
By the way, we have no idea what Final_set_page is...
function Final_Set() {
useEffect(() => {
console.log(1);
Final_set_page(); // I don't know what it is, so leaving it here. Move it if it is a component.
}, []); // [] empty dependency array means useEffect only runs once.
return (
<div id="exercise_sets_decider_box">
exercise_sets_decider_box
</div>
);
}
function App() {
const [mode, setMode] = useState("0"); // SetMode does not follow the convention for naming variables.
const handlePurpleBox1Click = () => setMode("Final"); // I moved this to separate functions so it is easier for you to edit them further.
const handlePurpleBox2Click = () => setMode("0");
if (mode === "0") {
return (
<div id="purple_box_1" onClick={handlePurpleBox1Click}>
purple_box_1
</div>
);
}
if (mode === "Final") { // if the previous return worked, this code is not reachable. This looks cleaner to me.
return (
<div>
<Final_Set></Final_Set>
<div id="practice"></div>
<div id="purple_box_2" onClick={handlePurpleBox2Click}>
purple_box_2
</div>
</div>
)
}
return <></> // add this, so the component returns something just in case.
}
I want to trigger long press event with click event. is there any way to that in react js?
something close to this, is the jQuery trigger() function. but i want something like trigger("longPress") or open up right click menu with left click in react. both mentioned (long press trigger / open up right click menu) are ideal for me
you can do this hack by get hold time
https://stackblitz.com/edit/react-d1txdm
export default function App() {
let triggerTime;
return (
<div>
<h1>Try on Google Chrome Desktop</h1>
<p>Open the console log to see how the event gets triggered.</p>
<p>The event should not get triggered if there is a long click.</p>
<img
src="https://via.placeholder.com/200.png/09f/fff"
onClick={(e) => {
if (triggerTime > 1000) return;
else console.log('normal click');
}}
onMouseDown={() => {
triggerTime = new Date().getTime();
}}
onMouseUp={() => {
let thisMoment = new Date().getTime();
triggerTime = thisMoment - triggerTime;
}}
/>
</div>
);
}
What about something like this:
const myComponent = () => {
let clickHoldTimer = null;
const handleMouseDown = () => {
clickHoldTimer = setTimeout(() => {
//Action to be performed after holding down mouse
}, 1000); //Change 1000 to number of milliseconds required for mouse hold
}
const handleMouseUp = () => {
clearTimeout(clickHoldTimer);
}
return (
<div onMouseDown={handleMouseDown} onMouseUp={handleMouseUp} />
)
}
I have a composent with which I would allow maintaining click in order to call multiple function by push-holding. My action dispatch a simple function to Redux reducers.
The objective of my component is to allow people decrease quantity of their order by maintaining a mouse's click. So that it, to allowing visitors have a more fluent user experience.
When I trigger the function my console returns me :
Cannot read property 'currentTarget' of undefined
When I click alone one time it is great. But when I mouseDown it fails with the above message.
Here my reactComponent.js:
import React, {Component} from 'react'
import style from "./OrderRibbon.css";
import equal from 'deep-equal';
export default class OrderRibbon extends Component {
t;
start = 100;
decreaseQuantity = (e) => {
e.preventDefault();
this.props.decreaseOrder(this.props.id)
}
addOrder= (e) => {
e.preventDefault();
this.props.addOrder(this.props.id)
}
orderPushing = (e) => {
e.preventDefault();
this.orderRepeat(e);
}
orderRepeat = (e) => {
if( e.currentTarget.attributes.name.value ){
console.log("EVENT NAME IN ORDER REAPEAT: ", e.currentTarget.attributes.name.value)
}else{
console.log("EVENT NAME IN ORDER REAPEAT: ", e.target.attributes.name.value)
}
if(e.currentTarget.attributes.name.value === "addOrder"){
this.addOrder
}else{
this.decreaseQuantity
}
this.t = setTimeout(this.orderRepeat, this.start);
this.start = this.start / 2;
}
// STOP Calling function
onMouseUp = () => {
clearTimeout(this.t);
this.start = 100;
}
render(){
return (
<div className={style.order_ribbon_layout} >
<div className={`${style.title} ${style.details_element}`} >
{this.props.title}
<div className={style.quantity} >
<div className= {style.quantity_icon}></div>
<span className= {style.quantity_number} > {this.props.quantity} </span>
</div>
</div>
<div className={style.price} >
{this.props.price * this.props.quantity}
</div>
<div className={style.quantity} >
<div
onMouseUp={this.onMouseUp}
onMouseDown={this.orderPushing}
name="decreaseQuantity"
onClick={this.decreaseQuantity}
className={ `${style.cardButton}`}
id={style.decreaseQuantity}></div>
<div
onMouseUp={this.onMouseUp}
onMouseDown={this.orderPushing}
name="addOrder"
onClick={this.addOrder}
className={ `${style.addButon}`}
// ${style.details_element}
id={style.addArticle}></div>
</div>
</div>
)
}
}
I wcan't figure out what is going wrong, if any body have an hint, would be great.
You have event binding issue. You can define like this:
orderPushing = () => (e) => {
e.preventDefault();
this.orderRepeat(e);
}
Or, keeping the same as you currently have, you may use inline event binding like this:
onMouseDown={(e) => this.orderPushing(e)}
I am working on a chat app, everytime I put a message I need to scroll to the bottom in order to see the new messages. So, as in a regular chat, I need to provide the functionality that the user may be able to see the last messages without manually scrolling to the bottom.
I am using React, is there a css way? or can you tell me the best way to do that ?
let me show you some code
this is the main component
render () {
let messages = this.props.chatMessages.map((message) => {
return <ChatItem info={message.info} me={message.me} player={message.player} message={message.message} />;
});
let chatForm;
if (this.props.mode === 'player') {
chatForm = <ChatForm onAddMessage={this.addMessage} />;
}
return <div className="Chat">
<ul className="Chat__messages">{messages}</ul>
<hr />
<div>{chatForm}</div>
</div>;
}
here are the ChatItem and ChatForm components
render () {
let item;
const { message, player, me, info } = this.props;
if (info) {
item = <li><em>{message}</em></li>;
}
else if (me) {
item = <li><strong>Me: {message}</strong></li>;
}
else {
item = <li><strong>{player}:</strong> {message}</li>;
}
return item;
}
render () {
return <div className="ChatForm">
<input
className="ChatForm__input"
placeholder="Your message..."
ref="newMessage"
onKeyDown={this.onKeyDown}
autofocus="true" />
</div>;
}
ADDING INFO
I need something like this http://codepen.io/TimPietrusky/pen/ylkFs
Look at this part
// Scroll the latest line of output
output.scrollTop(
output[0].scrollHeight - output.height()
);
how should I adapt it to my code on React ?
One way to do it is to compare current and previous/next props in a lifecycle event such as componentDidUpdate and scroll to bottom if a new message was added. For example:
componentDidUpdate(prevProps) {
// Check if new message was added, for example:
if (this.props.messages.length === prevProps.messages.length + 1) {
// Scroll to bottom
}
}