I have a progressBar in my React component.The progressBar is as shown below in the image:
So, when I am in the second page, the style be as shown below:
And the next image is for the third page:
So, what I have done is I have created the styling for the second page.
The code looks like this:
<div className={classes.sceProgressBar}>
<div className={classes.sceProgressBarText}>
<i className={ 'fas fa-check ' + this.progressBarStyleHandler} />
</div>
</div>
<hr className={classes.sceProgressBarUnderline} />
<div className={classes.sceProgressBarSecondText}>
<div className={classes.sceProgressBarText}>2</div>
<hr className={classes.sceProgressBarSecondUnderline} />
</div>
<div className={classes.sceProgressBarThirdText}>
<div className={classes.sceProgressBarText}>3</div>
</div>
Now what I want is, I want to make it a common component, so that for each page I don't have to add the style,I can directly import the page and show which page it is by passing the page details in the props.
So, I have added 9 states :
this.state = {
firstPage: false, //white background for Progress Bar
secondPage: false,
thirdPage: false,
firstPageDisplay: false, //green background for Progress Bar
secondPageDisplay: false,
tihrdPageDisplay: false,
firstPageCompleted: false, //tick mark for Progress Bar
secondPageCompleted: true,
thirdPageCompleted: false
};
And, I have added a function where it will check the value of the state which will determine which page it is in.The function looks like this:
progressBarStyleHandler = () => {
let progressbarClassname;
if (this.state.firstPageCompleted) {
progressbarClassname = classes.sceCheckIcon;
}
return progressbarClassname;
}
But for my current page, the function is not working, i.e. its not taking the className. What is wrong with my code?Can anyone please help me with that. Also, if anyone can suggest a better way of doing it, I will follow the same.
You are not actually calling your style handler.
You need to have className={'fas fa-check ' + this.progressBarStyleHandler()} instead of className={'fas fa-check ' + this.progressBarStyleHandler}.
But your approach of managing three booleans per page will not scale well. What if you want to re-use this component and have additional steps? I suggest an approach like below:
function Step({ number, status="NOT_DONE" }) {
switch (status) {
case "DONE":
return <div className="done"><i className="fas fa-check"/></div>
case "CURRENT":
return <div className="active">{number}</div>
case "NOT_DONE":
default:
return <div className="not-done">{number}</div>
}
}
function ProgressBar({ numberOfSteps = 0, currentStep = 0 }) {
if (!numberOfSteps) return null;
const steps = [];
for (let i = 0; i < numberOfSteps; i++) {
const status = i < currentStep ? 'DONE' : i === currentStep ? 'CURRENT' : 'NOT_DONE';
steps.push(<Step number={i} status={status} />)
}
return (
<div>
{steps}
</div>
)
}
And then it can be used like <ProgressBar numberOfSteps={3} currentStep={1}/>
Related
In the image as you can see, I have a Foo page, where I have 10 Accordions, In one of the Accordions there is a Form component, When I submit the Form it calls a remote API and returns some JSON data, I convert it to a Table of content and want to show it under the Form.
The problem is I can show the Table after toggling the Accordion again after the submit button clicked, as I have set the maxheight in the onClick.
const [activeState, setActiveState] = useState("");
const [activeHeight, setActiveHeight] = useState("0px");
const toogleActive = () => {
setActiveState(activeState === "" ? "active" : "");
setActiveHeight(activeState === "active" ? "0px" :`${contentRef.current.scrollHeight}px`)
}
return (
<div className={styles.accordion_section}>
<button className={styles.accordion} onClick={toogleActive}>
<p className={styles.accordion_title}>{title}</p>
</button>
<div ref={contentRef}
style={{ maxHeight: `${activeHeight}` }}
className={styles.accordion_content}>
<div>
{content}
</div>
</div>
</div>
)
I have used context also to share the useState hook between Accordion and Form components to update the height.
<UpdateHeightContext.Provider value={{updateHeight, setUpdateHeight}}>
<Accordion title="Find your Data" content={< FormWithTwoInput firstLabel="FirstName" secondLabel="LastName" buttonColor="blue" buttonText="Check Deatils"/>} />
</UpdateHeightContext.Provider>
Is there any way to update the Accordions height dynamically when I receive the response from the API? Other than toggling it again. A similar question was asked here React accordion, set dynamic height when DOM's children change unfortunately no one replied.
Even though the working around what I have found is not a robust one, but it is working completely fine for me. If someone stumbles upon this same issue might find this useful.
import React, { useState, useRef } from 'react'
const Accordion = ({ title, content }) => {
const [activeState, setActiveState] = useState("");
const [activeHeight, setActiveHeight] = useState("0px");
const contentRef = useRef("form")
const toogleActive = () => {
setActiveState(activeState === "" ? "active" : "");
setActiveHeight(activeState === "active" ? "0px" :`${contentRef.current.scrollHeight + 100}px`)
}
return (
<div className={styles.accordion_section}>
<button className={styles.accordion} onClick={toogleActive}>
<p className={styles.accordion_title}>{title}</p>
</button>
<div ref={contentRef}
style={{ maxHeight: `${activeHeight}` }}
className={styles.accordion_content}>
<div>
{content}
</div>
</div>
</div>
)
}
Accordion.propTypes = {
title: PropTypes.string,
content: PropTypes.object,
}
export default Accordion
I have hardcoded some extra space so that while the dynamic response is accepted the Table content is shown. In the CSS module file, I have kept the overflow as auto, earlier it was hidden.
.accordion_content {
background-color: white;
overflow: auto;
max-height: max-content;
}
As a result, the Table is appearing dynamically and the user can scroll inside the Accordion if my Table needs larger space.
I am working on a personal project where I need to get status of all devices within a unit. This status along with device name is returned in array from function deviceStatus(). If all the devices are ON, the home icon beside unit.id would turn green. If all devices within that unit are OFF, the home icon would turn red. This code works very well as shown below.
I am looking for help to display array returned from deviceStatus() as text box pop up when mouse hovers over the 'home' icon. I am very confused about mouseover event, any help would be highly appreciated.
<template>
<div>
<div class="d-flex flex-row align-items-center py-2 px-2">
<h1 class="display-1 unit-status m-0">{{ unit ? unit.id : null }}</h1>
<font-awesome-icon
icon="home"
:style="deviceStyling"
class="tab-icon mx-2"
size="lg"
id="unit-info"/>
</div>
</template>
<script>
export default {
computed: {
deviceStatus() {
const device = this.unitDvc(this.currentSite.id);
return device.map(dv => {
const status = this.deviceStat(dv.device_id);
return { name: dv.name, status };
});
},
deviceStyling() {
var turnedOn = null;
var turnedOff = null;
for (var i = 0; i < this.deviceStatus.length; i++) {
if (this.deviceStatus[i]['state'] == 'on') {
turnedOn = turnedOn + 1;
} else {
turnedOff = turnedOff + 1;
}
}
if (turnedOn == this.deviceStatus.length) {
return { 'color': `green` };
} else if (turnedOff == this.deviceStatus.length) {
return { 'color': `red` };
}
}
},
</script>
Be sure to have installed the v-tooltip dependency
npm install --save v-tooltip
and added to your app
import Vue from 'vue'
import VTooltip from 'v-tooltip'
Vue.use(VTooltip)
Then you can add the directive to your component:
<font-awesome-icon
v-tooltip="'Status is ' + deviceStatus.name"
icon="home"
:style="deviceStyling"
class="tab-icon mx-2"
size="lg"
id="unit-info"/>
As you mentioned you are using HTML and JavaScript, You could use the simple attribute of HTML i.e TITLE. It works simply as mouseover on that.
More Info: Title - MDN
I am working on a React application where I am trying to render text on the screen when a button is clicked. I have defined a function onButtonClick which gets triggered whenever the button is clicked. However, the HTML that I am returning from the function is not rendered on the screen. I am in the learning stages of React so please excuse me if the question seems silly.
class App extends Component {
constructor() {
super();
this.state = {
blockno:0
}
}
OnButtonClick = () => {
this.setState({blockno: this.state.blockno + 1})
return(
<div>
<h3>Some text</h3>
</div>
);
}
render() {
return(
<div>
<Button onButtonClick={this.OnButtonClick}/>
</div>
);
}
}
The value is being returned, but the framework/browser/etc. has no reason to do anything with that value.
Try thinking about this a different way, a "more React way". You don't want to return the value to be rendered, you want to update state. Something like this:
constructor() {
super();
this.state = {
blockno:0,
showDiv: false // <-- note the new property in state
}
}
OnButtonClick = () => {
this.setState({blockno: this.state.blockno + 1, showDiv: true})
}
Now you're not returning anything, but rather updating the state of the component. Then in your render method you conditionally render the UI based on the current state:
render() {
return(
<div>
<Button onButtonClick={this.OnButtonClick}/>
{
this.state.showDiv
?
<div>
<h3>Some text</h3>
</div>
: ''
}
</div>
);
}
The click handler doesn't modify the page, it just modifies the state of the component you're writing. The render method is responsible for rendering the UI based on that state. Any time state changes, render will be called again to re-render the output.
(Note: It's not 100% clear if this is exactly the functionality you're looking for in the UI, since it's not really clear what you're trying to build. But the point here is to illustrate how to update state and render output in React. Your logic can be tweaked as needed from there.)
You have to make a render based on your state. Please check the tutorial at the react docs to learn more about how React works. It's really good
Here is a version of your code that works. Hope it helps
class App extends Component {
constructor() {
super();
this.state = {
blockno: 0
};
}
OnButtonClick = () => {
//updates the states
this.setState({ blockno: this.state.blockno + 1 });
};
//remember: every time there is an update to the state the render functions re-runs
render() {
//variable holding the blocks in an array
let blocks = []
//if blockno is greater than 0, it checks everytime that there is a state change
if (this.state.blockno > 0) {
//for every block added
for (let index = 0; index < this.state.blockno; index++) {
//We`re going to add to the array of blocks a new div with the block number
blocks.push(
<div>
<h3>My block number is {index}</h3>
</div>
);
}
}
return (
<div>
<div>
{/**button that updates the state on every click */}
<button onClick={this.OnButtonClick}>
Click me to add a new div!
</button>
</div>
{/**This render the blocks variable that holds the divs */}
{blocks}
</div>
);
}
}
What I see is that you are trying to build a counter. The value that you're returning from the click handler function can't be rendered, instead you need to manage it in the render function as follow:
class App extends Component {
constructor() {
super();
this.state = {
blockno: 0
}
}
OnButtonClick = () => {
this.setState(prevState => ({ blockno: prevState.blockno + 1 }));
}
render() {
return(
<div>
{this.state.blockno > 0 && <div>some text {this.state.blockno}</div>}
<Button onButtonClick={this.OnButtonClick} />
</div>
);
}
}
Also note that the setState method is asynchronous, please read the documentation https://reactjs.org/docs/react-component.html#setstate
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)
}
I am new to ReactJS and I was wondering what is the correct way to target next element with same class in react?
<div className="portfolioGallery">
<img className="portfolioImg activeImg" src="img/1.png"/>
<img className="portfolioImg" src="img/2.png"/>
<img className="portfolioImg" src="img/2.png"/>
<div className="portfolioNext" onClick={this.nextImg.bind(this)}>
Next image
</div>
</div>
What would be the correct way that when I click the portfolioNext div I would be able to give the img2 class of activeImg and remove it from the previous element and so on in ReactJS?
Thank You!
constructor() {
super();
this.state = {
default: "portfolioImg activeImg"
};
}
nextImg() {
this.setState({
default: "portfolioImg"
});
}
That's the kind of imperative technique that you'd generally find in jQuery code, but it doesn't map very well to React's slightly more declarative nature.
Rather than trying to find the next element with a class, use state to maintain a list of those elements alongside an index cursor.
// constructor
this.state = {
images = ['img/1.png', 'img/2.png', 'img/3.png']
cursor: 0
};
Then use these bits of data to render your view.
// render
const { images, cursor } = this.state;
return (
<div>
{images.map((src, index) => {
const activeClass = (index === cursor) ? 'activeImg' : '';
return <img className={`portfolioImg ${activeClass}`} />;
}}
</div>
);
To change the active image, use setState to change the cursor property.
// nextImg
const { cursor, images } = this.state;
const nextCursor = cursor % images.length;
this.setState({ cursor: nextCursor });
I wouldn't suggest you think of it as siblings finding each other, but instead thing of it as the parent storing an index of the current children, and updating that instead.
this.props (or this.state) would have something like this (pseudocode)
this.props.images => ["img/1.png", "img/2.png", "img/2.png"];
Inside render:
<div className="portfolioGallery">
{this.props.images.map((image, i ) => active === i ? (<img className="portfolioImg activeImg" src="image" key={i}/>) : (<img className="portfolioImg " src="image" key={i}/>))}
<button className="portfolioNext" onClick={(e) => this.setState({active: this.state.active + 1}).bind(this)}>Next image</button>
</div>
Of course, accounting for when active >= images.length, but you get the idea