State applies to a group of elements instead of individual - reactjs

The idea is: I have 10 buttons, when I click on one button the recognition starts and the color of this button changes, when the recognition stops the button's color changes back to its initial.
But the problem is, when I click on the button, all buttons change its color and when the recognition stops, all 10 buttons change its color back to the initial one.
I keep the state of recognition (true/false) in useState: const [listening, setListening] = useState(false).
Then I map via array of buttons and check if recognition is listening - true otherwise - false:
<button
onClick={() => {
startRec(phrases.transcript)
}}
>
{!listening ? (
<img src="/recognize_phrase.png" width={40} height={40} />
) : (
<img src="/recognize_phrase_active.png" width={40} height={40} />
)}
</button>

You can take another state that stores the index (taken during the mapping array) of the button clicked, so if the id of a button matches with the state it changes its appearance.
<button
onClick={() => {
setId(id);
startRec(phrases.transcript)
}}
>
{(!listening && (idx != id)) ? (
<img src="/recognize_phrase.png" width={40} height={40} />
) : (
<img src="/recognize_phrase_active.png" width={40} height={40} />
)}
</button>
This ensures that the appearance of the button clicked is only changed.

Related

Field Array in React using formik

I wanted to follow like a todo list. Something just like in the picture below.
Right now, the problem with my code is that, its working differently.
I wanted only one input that renders a list of divs instead of input fields.
Exactly just like in the picture below:
Pls check my codesandbox here
CLICK HERE
<FieldArray
name="todos"
render={(arrayHelpers) => (
<div>
{formik.values.todos.map((friend, index) => (
<div key={index} style={{ display: "flex", gap: "1rem" }}>
<input
name={`todos[${index}].name`}
value={formik.values.todos[index].name}
onChange={formik.handleChange}
/>
<button
disabled={formik.values.todos?.length === 1}
type="button"
onClick={() => arrayHelpers.remove(index)}
className="deleteButton"
>
Remove
</button>
</div>
))}
<button
type="button"
onClick={() => arrayHelpers.push({ name: "" })}
>
Add
</button>
</div>
)}
/>
Here is a very simple and rude approach - I used Formik my project some time ago and I'm pretty sure it's not perfect but this is exactly what you need.
So some details.
do not render input for every item in your list, you need only render it's value and element with delete handler
you need only one controlled input and it's value is used for name field in your todos. State is cleaned when you click Add button.
you need to render your element only if formik.values.todos.lenght > 0
you need to disable Delete button when formik.values.todos.lenght === 1
Add button should be disabled when newValue.lenght === 0
Piece a cake, right?

loading spinner doesn't show up after clicking button with tailwind css and reactjs

I have a button to calculate statistics, what I want is that button change after clicking on it to calculating with animated load spinner, this is what I tried
<button className="bg-green-A200 rounded text-black mt-20 py-2 px-8 h-28" onClick={consulterStat} disabled={loading}>
{loading && (
<i
className="fa fa-refresh fa-spin animate-spin "
style={{ marginRight: "20px" }}
/>
)}
{loading && <span>calculate</span>}
{!loading && <span>calculating</span>}
</button>
When I click on button this what i do
setLoading(true)
setTimeout(() => {
setLoading(false)
}, 2000);
And this part works because every time I click the text change from calculate to calculating for 2 seconds, but what I want is to get the same button with the same style and everything just with different text and an animated circle spinner showing inside the button beside the text calculating.

UI kitten Button custom mapping not working

I'm trying to remove the margin horizontal that is applied to the button text but I'm unable to remove it
and also when I change the category it is not getting applied, can someone provide me with a an example on how to remove the button text margin (using custom mapping)
Here is the code for the category also
<Button
status="primary"
size="tiny"
appearance="ghost">
{(props) => (
<Text {...props} category="p1">
Edit
</Text>
)}
</Button>
Did you mean this?
<Button
status="primary"
size="tiny"
appearance='ghost'
style={{width: 0}}
>
{(props) => (
<Text {...props} category="p1">
Edit
</Text>
)}
</Button>
Snack

How to make the Collapse position to bottom-right after clicking on expand icon in AntD

I am using AntD Collapse for displaying a list of items after expand icon is clicked.
I want the position of expandIcon to go to bottom-right after all the list of the data when expand icon is clicked (just like in google news), but found only two options (left|right) for 'expandIconPosition', no option for top or bottom.
How can we align the expandIcon to bottom-right, when expand icon is clicked?
Few lines from the code for reference:
<Collapse
ghost
style={{ marginTop: "-1vh" }}
expandIcon={({ isActive }) => (
<DownOutlined
style={{ marginTop: "-2vh" }}
rotate={isActive ? 180 : 0}
/>
)}
expandIconPosition="right"
>
<Panel>
<div>
{list()} //list of items
</div>
</Panel>
</Collapse>
Here's one possible solution. Make Collapse a controlled component by specifying activeKey prop and then the value of it will be based on state. Then, by tracking the activeKeys state you can now do a conditional rendering (hide and show) on icons:
const [activePanelKeys, setActivePanelKeys] = useState([]);
const handlePanelIconClick = (panelKey, makeActive) => {
if (makeActive) {
setActivePanelKeys([...activePanelKeys, panelKey]);
} else {
setActivePanelKeys(activePanelKeys.filter((aPK) => aPK !== panelKey));
}
};
<Collapse
activeKey={activePanelKeys}
expandIconPosition="right"
expandIcon={() => <DownOutlined />}
// expandIcon={(panelProps) => (
// <DownOutlined
// onClick={() => handlePanelIconClick(panelProps.panelKey, true)}
// />
// )}
onChange={e => setActivePanelKeys(e)} //if you want to click only icon, comment this and uncomment the above expandedIcon
>
<Panel
header="This is panel header 1"
key="p1"
showArrow={activePanelKeys.indexOf("p1") === -1}
>
<div>{text}</div>
{activePanelKeys.indexOf("p1") !== -1 && (
<div style={{ textAlign: "right", marginTop: 10 }}>
<UpOutlined onClick={() => handlePanelIconClick("p1", false)} />
</div>
)}
</Panel>
{/* <PanelContent header="This is panel header 2" key="p2">
{text}
</PanelContent> */}
</Collapse>;
Here is the complete sample code:
Note: I tried to make a reusable Panel component but it seems that the reveal animation were gone. You can uncomment the commented PanelContent on the code to see the difference.
Hope that I hit what you want.

Influence tab order of Material UI controls

I have an app built up with React and Material UI. Within one view it is possible to have several text fields and several buttons. Now, when I have the focus on one text field and then press Tab I cannot reliably anticipate which one of the controls will be the next one to get the focus. I want to first tab through all the text fields and then secondly tab through all the buttons.
<DialogContent>
<DialogContentText>
The username and password that were used are incorrect. Please provide the correct credentials in order to login to the API.
<Stepper activeStep={this.state.credentialsStep} orientation='vertical'>
{
this.steps.map((label, index) => (
<Step key={label}>
<StepLabel>{label}</StepLabel>
<StepContent>
<Typography>{this.stepContent[index]}</Typography>
{this.stepAction[index]}
<Grid container direction='row' className='m-t-26'>
<Button color='primary'
onClick={() => {
this.state.credentialsStep === 0 ? this.onClickCancel() : this.onClickBack();
}}>
{this.state.credentialsStep === 0 ? 'Cancel' : 'Back'}
</Button>
<Button variant='contained'
color='primary'
onClick={() => {
this.state.credentialsStep === this.steps.length - 1 ? this.onClickLogin() : this.onClickNext();
}}>
{this.state.credentialsStep === this.steps.length - 1 ? 'Login' : 'Next'}
</Button>
</Grid>
</StepContent>
</Step>
))
}
</Stepper>
</DialogContentText>
</DialogContent>
Is there a way to set the tab order of controls?
You can control this with the tabIndex property, but you may be better off to figure out how to have the elements appear in the source in the order you would want the focus to go.
I have found this resource handy: https://bitsofco.de/how-and-when-to-use-the-tabindex-attribute/
When to use a positive tabindex value
There is almost no reason to
ever use a positive value to tabindex, and it is actually considered
an anti-pattern. If you’re finding the need to use this value to
change the order in which elements become focusable, it is likely that
what you actually need to do is change the source order of the HTML
elements.
One of the problems with explicitly controlling tabindex order is that any elements with a positive value are going to come before any other focusable elements that you haven't explicitly put a tabindex on. This means that you could end up with very confusing focus order if you miss any elements that you would want in the mix.
If you want to have the button on the right come before the button on the left in the focus order, there are various CSS options that would allow the button on the right to come first in the source order.
If, however, you decide that explicitly specifying the tabindex is your best option, here is an example showing how to do this for TextField and Button:
import React from "react";
import ReactDOM from "react-dom";
import TextField from "#material-ui/core/TextField";
import Button from "#material-ui/core/Button";
function App() {
return (
<div className="App">
<TextField label="1" inputProps={{ tabIndex: "1" }} />
<br />
<TextField label="3" inputProps={{ tabIndex: "3" }} />
<br />
<TextField label="2" inputProps={{ tabIndex: "2" }} />
<br />
<Button tabIndex="5">Button 5</Button>
<Button tabIndex="4">Button 4</Button>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
You may want to use the html attribute tabindex. This allows you to specify the order that tabbing will go through in your form. You can read more about it here and I've put a small example below, setting the tab index of your button to #1
<StepContent>
<Typography>{this.stepContent[index]}</Typography>
{this.stepAction[index]}
<Grid container direction="row" className="m-t-26">
<Button
tabIndex="1" // This will make the button the first tab index for the form.
color="primary"
onClick={() => {
this.state.credentialsStep === 0
? this.onClickCancel()
: this.onClickBack();
}}
>
{this.state.credentialsStep === 0 ? "Cancel" : "Back"}
</Button>
<Button
variant="contained"
color="primary"
onClick={() => {
this.state.credentialsStep === this.steps.length - 1
? this.onClickLogin()
: this.onClickNext();
}}
>
{this.state.credentialsStep === this.steps.length - 1 ? "Login" : "Next"}
</Button>
</Grid>
</StepContent>;
You can use a css trick to render the buttons in reverse order, but with css to reverse the buttons in UI.
<DialogContent>
<DialogContentText>
The username and password that were used are incorrect. Please provide the correct credentials in order to login to the API.
<Stepper activeStep={this.state.credentialsStep} orientation='vertical'>
{
this.steps.map((label, index) => (
<Step key={label}>
<StepLabel>{label}</StepLabel>
<StepContent>
<Typography>{this.stepContent[index]}</Typography>
{this.stepAction[index]}
<Grid container direction='row' className='m-t-26'>
// Box wrapper added <Box style={{ display: 'flex', flexDirection: 'row-reverse', justifyContent: 'flex-end' }}>
// First Button is now "Next in JSX <Button variant='contained'
color='primary'
onClick={() => {
this.state.credentialsStep === this.steps.length - 1 ? this.onClickLogin() : this.onClickNext();
}}>
{this.state.credentialsStep === this.steps.length - 1 ? 'Login' : 'Next'}
</Button>
<Button color='primary'
onClick={() => {
this.state.credentialsStep === 0 ? this.onClickCancel() : this.onClickBack();
}}>
{this.state.credentialsStep === 0 ? 'Cancel' : 'Back'}
</Button>
</Box>
</Grid>
</StepContent>
</Step>
))
}
</Stepper>
</DialogContentText>
</DialogContent>

Resources