I have a Gallery in my web application that I imported using 'React-Photo-Gallery.'
I am able to populate the gallery with images, and open up a photo carousel on click. How can I retrieve the index of the image clicked using the onClick method? activeIndex is set by default to 0, so upon clicking on any image, the first image in the array is displayed. I would like the clicked image to display in the carousel/Lightbox.
const mappingFunction = (img, index) => ({index, src: img.url, sizes: ["(min-width: 480px) 20vw,(min-width: 1024px) 25vw,25vw"], width: 4, height: 3});
const photosForGallery = images.map(mappingFunction)
After mapping the images, I display it like so:
<Gallery photos={photosForGallery} direction={"column"} columns={4} onClick={() => this.setState({ activeIndex: *use index here*, isOpen: true })} />
{isOpen && (
<Lightbox
mainSrc={urls[activeIndex]}
mainSrcThumbnail={urls[activeIndex]}
nextSrc={urls[(activeIndex + 1) % urls.length]}
nextSrcThumbnail={urls[(activeIndex + 1) % urls.length]}
prevSrc={urls[(activeIndex + urls.length - 1) % urls.length]}
prevSrcThumbnail={urls[(activeIndex + urls.length - 1) % urls.length]}
onCloseRequest={() => this.setState({ isOpen: false })}
onMovePrevRequest={() =>
this.setState({
activeIndex: (activeIndex + urls.length - 1) % urls.length
})
}
onMoveNextRequest={() =>
this.setState({
activeIndex: (activeIndex + 1) % urls.length
})
}
/>
)}
Where I'm having difficulty is accessing the index of the selected image. I've tried using the 'this' keyword, and even tried implementing a callback function. However (correct me if I'm wrong), it seems like the selected element on click is the Gallery itself, rather than my image of choice. Any input would be appreciated, as I'm new to React / JS.
Will continue to update my question as I do more research, though any input is appreciated.
For component Gallery onClick function:
Optional. Do something when the user clicks
a photo. Receives arguments event and an object containing the index,
Photos obj originally sent and the next and previous photos in the
gallery if they exist
http://neptunian.github.io/react-photo-gallery/api.html
So all you may have to do is as below in order to get an index:
<Gallery
photos={photosForGallery}
direction={"column"}
columns={4}
onClick={(e, { index }) => this.setState({ activeIndex: index, isOpen: true })} /> // <---- HERE
Related
I am facing a weird situation while working with React. We have a custom control in Dynamics 365 in what we use a dynamic inputs generated via Add button and removing with Delete button. And since the labels of the inputs include "1st", "2nd" etc., we need to re-render the correct labels.
Example: If there are up to 3 inputs "1st Renewal", "2nd Renewal" and "3rd Renewal", when user deletes the 2nd input, the 3rd should refresh to "2nd Renewal".
Behind the scenes, we work with an array of numbers, from where we generate Fluent UI elements.
const getIndexationPeriodPrefixFor = (numberPrefix: number) => {
return `${getNumberPrefix(numberPrefix)} Renewal`;
}
const generateDynamicContractedValues = () : IContractedValue[] => {
let dynamicValues = new Array<IContractedValue>();
props.contracted_prices.forEach((value, index) => {
dynamicValues.push(new ContractedValue(getIndexationPeriodPrefixFor(index + 1), value));
});
if (dynamicValues.length == 0) {
// Create initial 1st Renewal input for new Contracted indexation type.
dynamicValues.push(new ContractedValue("1st Renewal", null));
}
return dynamicValues;
};
const dynamicContractedValuesElements =
dynamicContractedValues.map((value, index) => {
return {
renewalPeriod: value.renewalPeriod,
renewalFragment: <>
<TooltipHost content="Renewal price agreed with the purchaser for the renewal period, excluded from indexation.">
<TextField required={index == 0} disabled={shouldBeInputDisabled}
type="number" id={`Input-Renewal-${index+1}`}
value={value.renewalPrice?.toPrecision()}
onKeyDown={e => ValidationService.PreventMinusSign(e)}
onChange={e => updateRenewal(e, index)}
suffix={props.currency.name}></TextField></TooltipHost><ActionButton id={`Btn-Remove-Renewal-${index+1}`} iconProps={{ iconName: "Delete" }} onClick={() => { removeRenewalLine(index) }} disabled={index < 1} hidden={shouldBeInputDisabled || index < 1}></ActionButton>
{doesRenewalPriceHaveUnexpectedValue && unexpectedPriceWarning}</>
}
})
const removeRenewalLine = (index: number) => {
let newContractedPrices = [...contractedPrices];
newContractedPrices.splice(index, 1);
setContractedPrices(newContractedPrices);
let newDynamics = generateDynamicContractedValues();
// We want to reload the number prefixes, when the user deletes a contracted period.
// Example: When user deletes 2nd Renewal, the 3rd Renewal should change to 2nd Renewal.
setDynamicContractedValues(newDynamics);
}
We generate the UI elements via the contracted_prices array with generateDynamicContractedValues method.
The problem is with the line
<ActionButton id={`Btn-Remove-Renewal-${index+1}`} iconProps={{ iconName: "Delete" }} onClick={() => { removeRenewalLine(index) }}
Specifically with the removeRenewalLine(index) method - it's not causing any change in UI for the first click of the user. When you click delete, the array behind the control is changed, but the input is not being deleted and then the prefixes recalculated -> just for the first click. From the second click it works just as I wanted.
Any ideas please? Thank you
Store the array in a useState. If it's just a variable, it's not reactive. Thus the DOM will not react to a change of the variable.
I'm creating a webpage slide show. I created a file called SlideshowData.js where I exported an array of objects with all image links and ids. So using react I mapped through the photos and added dots to them. I created the dots and each time the photos switch the dot changes color from gray to black to indicate that the current photo is active.
The problem occurs now that I keep trying to figure out how to make them clickable. So for example you would click on the first dot it would bring you to the first slide. I tried to do it with a "set.state" function and set the initial index to the "event.target.key" which I assigned slide.id but it doesn't work.
Thank you for your time. I attached the code below.
class Slideshow extends React.Component{
constructor(props){
super(props);
this.state = {
index: 0,
delay: 5000,
length: SlideshowData.length,
}
this.clickedDot = this.clickedDot.bind(this)
}
componentDidMount(){
document.addEventListener("onClick", this.clickedDot)
if(this.state.index === this.state.length -1){
setTimeout(()=> this.setState(()=>({
index: 0
})),this.state.delay)
}else{
setTimeout(()=> this.setState((state)=>({
index: state.index + 1,
})),this.state.delay)
}
}
componentDidUpdate(){
document.addEventListener("onClick", this.clickedDot)
if(this.state.index === this.state.length -1){
setTimeout(()=> this.setState(()=>({
index: 0
})),this.state.delay)
}else{
setTimeout(()=> this.setState((state)=>({
index: state.index + 1,
})),this.state.delay)
}
}
clickedDot(){
this.setState((slide) =>({
index: this.state.length
}))
console.log(this.state.index)
}
render(){
return(
<div className="slidesContainer">
<div className="SlideshowSlider" style={{ transform: `translate3d(${-this.state.index * 100}%, 0, 0)` }}>
{SlideshowData.map((slide,index) => (
<img className="slides" src={slide.image} key={index} alt="travel"/>
))}
</div>
<div className = "slideshowDots">
{SlideshowData.map((slide,idx) => (
<div onClick={this.clickedDot} key ={slide.id} className={`slideDot${slide.id === this.state.index ? " active" : ""}`} ></div>
))}
</div>
</div>
)
}
}
export default Slideshow
You can pass the index inside your onClick function on the dots such as this:
<div onClick={(idx) => this.clickedDot(idx)} key ={slide.id} className={`slideDot${slide.id === this.state.index ? " active" : ""}`} >
and then use the index to change the slide accordingly in your clickedDot function.
I have a function which creates 2 divs when changing the number of items correspondingly (say if we choose 5 TVs we will get 5 divs for choosing options). They serve to make a choice - only one of two possible options should be chosen for every TV, so when we click on one of them, it should change its border and background color.
Now I want to create a dynamic stylization for these divs: when we click on them, they should get a new class (tv-option-active) to change their styles.
For that purposes I used 2 arrays (classesLess and classesOver), and every time we click on one of divs we should remove a class if it's already applied to the opposite option and push the class to the target element - thus only one of options will have tv-option-active class.
But when I click on a div I do not get anything - when I open the document in the browser and inspect the elements, the elements do not even receive new class on click - however, when I console log the classes variable that should apply to an element, it is the way it should be - "less tv-option-active" or "over tv-option-active". I applied join method to remove the comma.
I checked the name of imported css file and it is ok so the problem is not there, also I applied some rules just to make sure the problem is not there and it worked when it's not dynamic (I mean no clicks are needed).
So my list of reasons causing that trouble seems to be not working.
I also tried to reorganize the code in order to not call a function in render return - putting mapping directly to render return, but this also didn't work.
Can anyone give me a hint why it is that?
Here is my code.
import React from 'react'
import { NavLink, withRouter } from 'react-router-dom'
import './TVMonting.css'
import PageTitle from '../../PageTitle/PageTitle'
class TVMontingRender extends React.Component {
state = {
tvData: {
tvs: 1,
under: 0,
over: 0,
},
}
render() {
let classesLess = ['less']
let classesOver = ['over']
const tvHandlers = {
tvs: {
decrease: () => {
if (this.state.tvData.tvs > 1) {
let tvData = {
...this.state.tvData,
}
tvData.tvs -= 1
this.setState({ tvData })
}
},
increase: () => {
if (this.state.tvData.tvs < 5) {
let tvData = {
...this.state.tvData,
}
tvData.tvs += 1
this.setState({ tvData })
}
},
},
}
const createDivs = () => {
const divsNumber = this.state.tvData.tvs
let divsArray = []
for (let i = 0; i < divsNumber; i++) {
divsArray.push(i)
}
return divsArray.map((i) => {
return (
<React.Fragment key={i}>
<div
className={classesLess.join(
' '
)}
onClick={() => {
const idx = classesOver.indexOf(
'tv-option-active'
)
if (idx !== -1) {
classesLess.splice(
idx,
1
)
}
classesLess.push(
'tv-option-active'
)
}}
>
Under 65
</div>
<div
className={classesOver.join(
' '
)}
onClick={() => {
const idx = classesLess.indexOf(
'tv-option-active'
)
if (idx !== -1) {
classesOver.splice(
idx,
1
)
}
classesOver.push(
'tv-option-active'
)
// classesOver.join(' ')
}}
>
Over 65
</div>
</React.Fragment>
)
})
}
return (
<div>
<button onClick={tvHandlers.tvs.decrease}>
-
</button>
{this.state.tvData.tvs === 1 ? (
<h1> {this.state.tvData.tvs} TV </h1>
) : (
<h1> {this.state.tvData.tvs} TVs </h1>
)}
<button onClick={tvHandlers.tvs.increase}>
+
</button>
{createDivs()}
</div>
)
}
}
export default withRouter(TVMontingRender)
CSS file is very simple - it just adds a border.
P.S. I know that with this architecture when I click on one of the divs all the divs will get tv-option-active class, but for now I just want to make sure that this architecture works - since I'm relatively new in React 🙂Thanks in advance!
Components won't have their lifecycle triggered if you are mutating a variable. You need a state for that purpose, which stores the handled data.
In your case you need some state to say which div has the active class, under or over. You can also abstract each rendered Tv to another Class component. This way you achieve independent elements that control their own class, rather than changing all others.
For that I created a Tv class, where I simplified some of the logic:
class Tv extends React.Component {
state = {
activeGroup: null
}
// this will update which group is active
changeActiveGroup = (activeGroup) => this.setState({activeGroup})
// activeClass will return 'tv-option-active' if that group is active
activeClass = (group) => (group === this.state.activeGroup ? 'tv-option-active' : '')
render () {
return (
<React.Fragment>
<div
className={`less ${ activeClass('under') }`}
onClick={() => changeActiveGroup('under')}
>
Under 65
</div>
<div
className={`over ${ activeClass('over') }`}
onClick={() => changeActiveGroup('over')}
>
Over 65
</div>
</React.Fragment>
)
}
}
Your TvMontingRender will be cleaner, also it's better to declare your methods at your class body rather than inside of render function:
class TVMontingRender extends React.Component {
state = {
tvData: {
tvs: 1,
under: 0,
over: 0,
}
}
decreaseTvs = () => {
if (this.state.tvData.tvs > 1) {
let tvData = {
...this.state.tvData,
}
tvData.tvs -= 1
this.setState({ tvData })
}
}
increaseTvs = () => {
if (this.state.tvData.tvs < 5) {
let tvData = {
...this.state.tvData,
}
tvData.tvs += 1
this.setState({ tvData })
}
}
createDivs = () => {
const divsNumber = this.state.tvData.tvs
let divsArray = []
for (let i = 0; i < divsNumber; i++) {
divsArray.push(i)
}
// it would be better that key would have an unique generated id (you could use uuid lib for that)
return divsArray.map((i) => <Tv key={i} />)
}
render() {
return (
<div>
<button onClick={this.decreaseTvs}>
-
</button>
{this.state.tvData.tvs === 1 ? (
<h1> {this.state.tvData.tvs} TV </h1>
) : (
<h1> {this.state.tvData.tvs} TVs </h1>
)}
<button onClick={this.increaseTvs}>
+
</button>
{this.createDivs()}
</div>
)
}
}
Note: I didn't change the key you are passing to Tv, but when handling an array that you manipulate somehow it's often better to pass an unique id identifier. There are some libs for that like uuid, nanoID.
When handling complex class logic, you may consider using libs like classnames, that would make your life easier.
im trying to create a react page with react-spring's parallax.Im using web api for data so when i use parallax tags im trying to set offset and scrollTo function's value.As you can see below;
class HomeComponent extends Component {
constructor(props) {
super(props);
this.state = {
list: [],
categoryCount: '',
}
}
componentDidMount() {
axios.get(`http://localhost:9091/api/category`)
.then(res => {
this.setState({ list: res.data, categoryCount: res.data.length })
});
}
so these are my declerations and web api call part, next part is render();
render() {
let i = 1
return <Parallax pages={this.state.categoryCount + 1} scrolling={true} vertical ref={ref => (this.parallax = ref)}>
<ParallaxLayer key={0} offset={0} speed={0.5}>
<span onClick={() => this.parallax.scrollTo(1)}>MAINPAGE</span>
</ParallaxLayer>
{this.state.liste.map((category) => {
return (
<ParallaxLayer key={category.categoryId} offset={i} speed={0.5}>
<span onClick={() => { this.parallax.scrollTo(i + 1) }}>{category.categoryName}</span>
{i += 1}
{console.log(i)}
</ParallaxLayer>
);
})}
</Parallax>
}
so in a part of this code, i am mapping the list for creating enough amount of parallax layer.But I can't manage the offset and this.parallax.scroll() 's values.These guys taking integer value for navigation to each other.
I tried the i and i+1 deal but it gets weird.First parallax works well it navigates the second page but after first page every page navigates me to the last page.I can't find a related question in stackoverflow so i need help on this one.Thanks for answers and sorry for my English.
After investigating the stackblitz, I see that the problem indeed was that the "i" value was increasing up to the list's length immediately, so wherever you clicked except for the first one, you were going to the last page.
I added a listIndex value to the map iteration, and incremented it there. You can follow the console.log statements, as well as the printed things on the screen.
This is a working solution but I'm more than certain there's a more elegant way to solve this (move it into a function etc).
render() {
let i = 1;
return <Parallax pages={this.state.liste.length + 1} scrolling={true} vertical ref={ref => (this.parallax = ref)}>
<ParallaxLayer key={0} offset={0} speed={0.5}>
<span onClick={() => this.parallax.scrollTo(1)}>MAINPAGE</span>
</ParallaxLayer>
{this.state.liste.map((category, listIndex) => {
return (
<ParallaxLayer key={category.categoryId} offset={listIndex + 1} speed={0.5}>
<span onClick={() => { this.parallax.scrollTo(listIndex + 1) }}>{category.categoryName} - test</span>
{listIndex += 1}
{console.log(listIndex)}
</ParallaxLayer>
);
})}
</Parallax>
}
Let me know if I can help with anything else.
I'm building a conference website using three of these tabs (#speaker, #talks, #schedule). I think it is fair to want interactions between the tabs, here are a couple use cases that I cannot seem to solve.
From the #talks tab, I click on the bio hash - #johnsmith. This id exists within the page, but since I don't first switch tab to #speakers, nothing renders.
If I want to reference a specific talk and email someone the url: https://website.com#speaker_name the tabs won't open, and nothing but the tabs render.
The problem is compounded by the fact that when I click on an anchor tag href using a '#id', I must reload the page for it to fire.
I feel like there should be some way to pass a parameter when changing the tab or something... I'm in a tough spot because I'm rolling out code, but need this functionality badly.
Here is the actual open-source repo - https://github.com/kernelcon/website. The code I'm referencing can be found in src/pages/Agenda/.
Here is some example code.
Agenda.js
<Tabs defaultTab={this.state.defaultTab}
onChange={(tabId) => { this.changeTab(tabId) }}
vertical={vert}>
<TabList vertical>
<Tab tabFor="speakers">Speakers</Tab>
<Tab tabFor="talks">Talks</Tab>
<span>
<TabPanel tabId="speakers">
<Speakers />
</TabPanel>
<TabPanel tabId="talks">
<Talks />
</TabPanel>
</span>
</Tabs>
Talks.js
changeTab(id) {
window.location.reload(false);
}
getTalks() {
// Order Alphabetically
const talksOrdered = speakerConfig.sort((a,b) => (a.title > b.title) ? 1 : ((b.title > a.title) ? -1 : 0));
const talks = talksOrdered.map((ele, idx) => {
const twitterUrl = ele.twitter.replace('#', '');
return (
<div id={ele.talk_id}
key={idx}
className='single-talk'>
<div className='talk-title'>{ele.title}</div>
<div className='talk-sub-title'>
<div className='speaker-name'>
<a onClick={() => {this.changeTab(ele.speaker_id)}}
href={`#${ele.speaker_id}`}>{ele.speaker}</a>
</div>
...
I ended up accomplishing this by sending #tab_title/speaker_name, then adding a componentWillMount lifecycle method and function in the main tab file like below.
componentWillMount() {
const defaultTab = this.props.location.hash ? this.props.location.hash.split('#')[1] : 'schedule';
this.setState({
defaultTab: defaultTab
});
this.handleHashChange();
window.addEventListener('hashchange', this.handleHashChange);
}
handleHashChange = () => {
// given `#speakers/dave` now you have tabName='speakers', speakerHash='dave'
const [tabName, speakerHash] = window.location.hash.replace('#', '').split('/');
const tabNamesToWatchFor = [
'schedule',
'speakers'
];
if (tabNamesToWatchFor.includes(tabName)) {
this.setState({
defaultTab: tabName,
// pass this.state.speakerHash to <Speakers/> and use this for scrollIntoView in componentDidMount
speakerHash: speakerHash
});
}
}
Next, I went to the individual tab (in this case Speakers.js) and added a componentDidMount and componentDidUpdate method to help scroll to the speaker itself.
componentDidMount() {
this.handleScrollToSpeaker(this.props.speakerHash);
}
componentDidUpdate(prevProps) {
if (prevProps.speakerHash !== this.props.speakerHash) {
this.handleScrollToSpeaker(this.props.speakerHash);
}
}
handleScrollToSpeaker = hash => {
window.setTimeout(() => {
const ele = document.querySelector(`#${hash}`);
if (ele) {
ele.scrollIntoView({ block: 'start', behavior: 'smooth' });
}
}, 500)
}