React Native Material - How to display loading when button is pressed - javascript

I am using React Native Material and i would like to use "loading" when a button is clicked. When the button is not clicked, it should only display the button.
Is it also possible when loading is displayed, it will disappear after 5 seconds or when i navigate to a different page?
I have tried to use an if statement when onPress is clicked to display loading but this displays an error.
https://www.react-native-material.com/docs/components/button
Code:
<Button
title="Submit Answers"
onPress={CalculateTotal}
loading
/>

Create a state variable for loading and set it false. So that whenever navigating to the component from another page, that will disable the loading.set loading true on button click and add a timeout for disabling it.
const [loading, setLoading] = useState(false);
const CalculateTotal =()=>{
setLoading(true);
setTimeout(()=>{
setLoading(false);
},5000)
}
<Button
title="Submit Answers"
onPress={CalculateTotal}
loading={loading}
/>

You need to create a loading state and change that state according to button press ex:
const [loading, setLoading] = useState(true);
return (
<Button
onPress={() => setLoading(!loading)}
title="Submit Answers"
onPress={CalculateTotal}
loading={loading}
/>
)

Related

React file input onChange not changing the picture?

I am getting a thumbnail from the user for a particular store. When the file Browse button is clicked, and an image is opened, this sets the thumbnail for the given store; however, I have also added a small x button on the top right of the thumbnail whose purpose in life is to remove this picture and to add a new one. The main problem that I am facing is when I select a thumbnail, and when I click on the x button, it removes the image, but if I choose the same drawn image, it does not add it as a thumbnail. So I have to select a different image to choose the old one.
import thumbnail from "../../../../Assets/thumbnail.png";
import deleteicon from "../../../../Assets/close.svg";
const thumbimage = dataType64toFile(thumbnail);
const [image, setImage] = useState(thumbimage);
const [filename, setFileName] = useState("Upload Image");
const [picture, setPicture] = useState(thumbnail);
const [close, setClose] = useState(false);
{close && (
<img
src={deleteicon}
alt="Delete Thumbnail"
className="thumbnail-close"
onClick={() => {
setImage(thumbimage);
setPicture(thumbnail);
setFileName("Upload Image");
setClose(false);
}}
/>
)}
<Form.File
type="file"
label={filename}
onChange={(e) => {
setImage(e.target.files[0]);
setFileName(e.target.files[0].name);
setPicture(URL.createObjectURL(e.target.files[0]));
setClose(true);
}}
custom
/>
I had recently created the same gallery of images, but my approach involved a custom hook file outside my component, i.e. I just put all my useStates and handler function outside and imported it from there.
first a tweak, don't use const [close, setClose] = useState(false); instead check using image.
set your file and image as null as and when you click delete icon
regarding thumbnail and other don't set em! instead place the icon in the container and when an image is selected let it cover it!

How to scroll down page using React button component?

I want to press a button and the page scrolls down automatically to the next piece of content. I know in HTML I'd use sections but for React I am still learning on how to create this function.
import Button from '#material-ui/core/Button';
function scrollDownPage(){
window.scrollTo(PageContent) <<<< I SCROLL THE PAGE DOWN TO PAGE CONTENT COMPONENT
}
function App() {
const style = useStyles();
return(
<Button
onClick={scrollDownPage} // <<<<<<<<<THIS
>
</Button>
<PageContent/>
)}

How to disable other buttons till the function call is complete after clicking on one in react render()?

My function call takes some time to produce display, if any other button is clicked the result is overlapped and that is not desired. I need to disable all toggle buttons until one function call is complete, including reset button. Also, please can anyone add how do I display my function runtime on render screen. I'm getting the time in console window, I need to display it on screen below my div.
return (
<div>
<button onClick={() => this.resetfunc()}>Reset</button>
<button onClick={() => this.func1()}>Function 1</button>
<button onClick={() => {const start = performance.now();
this.func2();
const end = performance.now();
console.log(end-start);}}>Function 2</button>
<button onClick={() => this.func3()}>Function 3</button>
</div>
);
React always renders your current state (in a broad sense). So, if you want something to change, you have to change your state.
For example, you can have "working" state. In this state your buttons would be disabled (generally bad idea from UX point of view). And then, in "not_working" state all buttons would be enabled. Your goal is to switch your state when needed.
And for time your function worked - state again. If you want render something, you have to either hardcode it (like "Function 2" text), or put into state (in a broad sense).
Try adding a state for tracking if data is processing. The same can be used after the data is set.
const [processing, setProcessing] = useState(false)
When clicking a button,
<button disabled={this.processing} onClick={() => (this.setProcessing(true);this.resetfunc())}>Reset</button>
Also don't forget to reset it in your function call (Or keep it hanging if you want the buttons permanently disabled)
const resetfunc = () => {
// Do something cool here
this.setProcessing(false)
}

Potential issue related to React hooks asked for job interview

So I have a React job interview and have this piece of code in my assignment to close and modal box:
const App = (): ReactElement => {
const [isOpen, setIsOpen] = useState<boolean>(false);
const renderApp = (): ReactElement => {
if (isOpen) {
return <FeedbackForm onClose={() => setIsOpen(false)} />;
}
return <button onClick={() => setIsOpen(true)}>Open modal</button>;
}
if (isOpen) {
return <>
<div className='App'>
<FeedbackForm onClose={() => setIsOpen(false)} />
</div>
</>
}
return <>
<div className='App'>{renderApp()}</div>
}
export default Feedback;
So here I have an App component that has a Modal component and a simple hook that has a boolean value that indicates if the modal is open or not. The modal starts off as closed, so the initial value is false. The button to open the modal is separate from the button that has to close the modal. The button to close the modal is within the Modal component while the button to open it is in the App component. Because they're both separate buttons, they can explicitly set the value to either true or false.
Now, on this topic, I received this question from the code reviewer:
Could you explain the potential issue of the following code?
const [isOpen, setIsOpen] = useState(false)
const toggle = () => setIsOpen(!isOpen);
I can't exactly see the problem in this snippet. I've tried running it with a button that calls toggle() and I see it updating the state perfectly fine. What is the potential issue the interviewer is talking about here?
In the toggle function, we are setting the state based on the current state value. React performs updates in batches and it is a possibility that when we run toggle() multiple times, the state is not updated for each subsequent run. So, to make sure that we don't lose the state updates from the previous runs, we can do something like the following:
const toggle = () => setIsOpen((prevIsOpen) => !prevIsOpen);
Now, in your scenario, it might not happen because we are showing/hiding modal based on toggle click which changes the views completely, but we can't be sure and can't take chances for production deployment. If it were something else, like showing/hiding of expansion panel, sidebar, etc. then the issue would be easily visible if you clicked toggle button simultaneously, with minimal delay between clicks.

React.js dialog component disappears yet remains in DOM

I'm using a Dialog component from Material-UI which, for the most part, is working correctly. However, if I click away from the Dialog, the Dialog will disappear (as expected) but sometimes, it remains in the DOM with its opacity set to 0, and I can't click anything else since the Dialog is in the way. This is a small sample of my code:
const [openDialog, setOpenDialog] = React.useState(false);
React.useEffect(() => {
// Get data for ReactTable
}, []);
return(
<div>
// Other components
<Button color="white" onClick={() => setOpenDialog(true)}>
Open Dialog
</Button>
// Other components
<Dialog open={openDialog} maxWidth="md" onClose={() => setOpenDialog(false)}>
// ReactTable and close button
</Dialog>
</div>
)
This bug doesn't always occur which makes it tricky to debug. I've only been using React for about a month, but I'm wondering if it's a state problem, or maybe some sort of race condition. Any suggestions?
Edit: This also occurs when a DropzoneDialog appears, to upload a file.
This also works:
<Dialog className={openDialog ? "" : classes.displayNone} open={openDialog} maxWidth="md" onClose={() => setOpenDialog(false)}>
// ReactTable and close button
</Dialog>
where in the styles file you have:
displayNone: {
display: "none"
}
In case anyone else has this same issue, I found the answer:
Elsewhere in the app, useEffect() was stuck in a loop and running extremely frequently which slowed the app down, causing this problem.

Categories