react-ticker
react-ticker copied to clipboard
index parameter is not reset for every iteration
As per the below example code:
const MoveStuffAround = () => (
<Ticker>
{({ index }) => (
<>
<h1>This is the Headline of element #{index}!</h1>
<img src="www.my-image-source.com/" alt=""/>
</>
)}
</Ticker>
)
I expected that the index value will be reset based on the number of children elements inside <Ticker>.
However, it seems to be a continuous counter value irrespective of the number of children. Because of this, after the first iteration through all messages, it goes out of bound of messages array - if one keeps messages in an array and use the index.
Either code should be fixed. Otherwise, the documentation needs to be fixed :)
The code I have:
// Notice the need for modulus operator
const getMessage = i => {
const messages = [
"message-0",
"message-1",
"message-2",
]
console.log("Value of i is: " + i%messages.length)
return (
<>
<div style={{ marginRight: "1rem" }}>
<p style={{ whiteSpace: "nowrap", color: "#e83e0a" }}>
{messages[i%messages.length]}
</p>
</div>
</>)
}
<Ticker mode="await" move={true}>
{({index}) => getMessage(index)}
</Ticker>
Hi, Did you get any solution?
You are right: index is a continuous counter, which has no relation to the elements itself. It just counts the event, react-ticker orders a new element. This is not mentioned in the docs so far, which needs to be changed.
I wrote a method that returns only one item from the list at a time. Used state to check and reset if list reach to last element. See my solution here:
import React, { useState } from "react"; import Ticker from "react-ticker"; import PropTypes from "prop-types";
const TickerComponent = props => { const [count, setCount] = useState(0); const getNewsItem = () => { if (count < props.data.length - 1) { console.log("befor calling setCount ", count); setCount(count + 1); console.log("count after::", count); } else { setCount(0); } const item = props.data[count];
return (
<>
<span>
{item.Description + " count::" + count}
</span>
</>
);
};
return ( <Ticker mode="await"> {() => getNewsItem()} </Ticker> ); };
TickerComponent.propTypes = { data: PropTypes.array };
export default TickerComponent;
I don't have an elegant way to solve this, but I have found a way to solve the issue.
const post=[1,2,3,4,5]; function Outpu(){ return <Ticker height={120} speed={20} > {({ index }) => ( <> <div style={{display: "none"}}> {index=index%posts.length} </div> <div> Your content here. </div> </> )} </Ticker>
}