I am using react hooks for my frontend designs and while creating a register form I have used various validations and I am depicting errors using reactstrap warning alerts.
And things are working fine but when focus is not implemented on these alers means when my page shows any of alert, it doesn't focus on that automatically.
I have tried basic codes for autofocus/ autoFocus or Focus() but nothing is working as per need.
My alert code look as shown below:
{
showAlreadyRegisteredAlert?
<Alert variant="warning" onClose={() => setShowAlreadyRegisteredAlert(false)} dismissible>
<p className="mb-0">
{content}
</p>
</Alert>
:null
}
I am just writing these alert codes in between my form inputs and whenever I need to call any of them I simply setValue for the commponent and alert box is called but still it lacks autofocus.
Any help will be appreciated. Thanks in advance!
I found the desired solution as I wanted my page should automatically focused on appearing alert boxes. I searched react-hooks official documention and get to know that we can use "useRef" for the purpose and below is my code for better understanding and clarification:
First: import useRef from react.
import React, {useState, useRef} from "react";
Second: create const with desired name using useRef as null.
const inputUser = useRef(null);
Third: set focus on your ref const after alert.
setShowAlreadyRegisteredAlert(true);
inputUser.current.focus();
Fourth: pass ref as const which you defined in step 2 inside your input field.
ref= {inputUser}
Related
I am trying to create an input with the autosuggest. As I am using tailwind, there is no this kind of input there and therefore I came across react-autosuggest. The thing is however, I need to use a ref for this Autosuggest Input, cause I need to submit after a select and logically get the value of this Autosuggest Input on button click/submit. Here is part of my code (not everything). The code was working with normal input, so ne help needed apart from fixing the Ref problem:
import { useState, useEffect, useRef } from 'react';
import Autosuggest from 'react-autosuggest';
export const SearchBar = () => {
const autosuggestInput = useRef(null);
....
const city = autosuggestInput.current.value;
......
return(
<Autosuggest
type="text"
ref={autosuggestInput}
className="py-3 px-4 block w-full shadow-sm focus:ring-blue-500 focus:border-blue-500 border-gray-300 rounded-md"
/>
)
}
Here I am getting the Error: Cannot read property 'value' of undefined. Which suggests that the ref is not working. I am using next.js and therefore also functional components. Maybe that is the problem?
By default your ref line won't do anything. Because ref only applies to the Host component, such as div, p, button etc.
<div ref={ref}>ABC</div>
The above line will work. Ok, so in order to get the ref onto a custom component, there's some ways. One is to use a forwardRef, however either way the interface of react-autosuggest needs to allow you do that. I just read a bit, doesn't seem so.
However if you just want the value, seems the documentation is asking you do this
const inputProps = {
placeholder: 'Type a programming language',
value,
onChange: this.onChange
};
return (
<Autosuggest
...
inputProps={inputProps}
/>
);
Try their demo first. Basically any input is driven by value and onChange. The rest of them are all sugar code.
React auto-suggest is a controlled component and so needs some mandatory parameters passed into it such as the value, suggestions, onChange handler etc. which is what is giving you the error and NOT useRef.
See Basic Usage here : https://www.npmjs.com/package/react-autosuggest
The following props need to be passed through to the AutoSuggest component (From the Basic Usage npm docs) :
// Finally, render it!
return (
<Autosuggest
suggestions={suggestions}
onSuggestionsFetchRequested={this.onSuggestionsFetchRequested}
onSuggestionsClearRequested={this.onSuggestionsClearRequested}
getSuggestionValue={getSuggestionValue}
renderSuggestion={renderSuggestion}
inputProps={inputProps}
/>
);
I am using an ant design modal on my site which is internationalized. The modal works fine for all languages except Arabic. When it is on Arabic, when you click the 'next' button, it should show you the next page of the modal, but it just shows a blank modal. I suspect because Arabic is a RTL language, this issue would be solved if I could get the modal to slide in the other direction when the user hits next. I see on Ant Design's documentation they have some mention of RTL functionality on the modal page, but I'm not sure how to implement it. It says
Modal.method() RTL mode only supports hooks.
but i'm not sure what it means by that.
On this configuration page it mentions a direction prop, but I passed it a string "rtl" and that didn't seem to have an effect. It says the prop type should be rtl or ltr, so it shouldn't take a string?
Use configProvider and wrap all antd components in it with direction="rtl". you can also apply it conditionally: direction={condition ? "rtl" : "ltr"}.
import { ConfigProvider } from 'antd';
// ...
export default () => (
<ConfigProvider direction="rtl">
<App />
</ConfigProvider>
);
Reference: https://ant.design/components/config-provider/?theme=dark#header
I am trying to implement a simple component (an animated hamburger menu button). Its class needs to be updated when it is active or not. For that point, I'm using a state hook.
I want to add a onClick property to this button to invert its state. But this onClick function is never firing.
When I set the button active by myself, the button appearence changes as I wanted.
I am using fullPage.js in my project.
I saw a lot of topic about that, but no one answered to my problem...
Thanks for future answers !
Here is my code :
import React, { useState } from 'react';
import './hamburger.css';
const MenuButton = () => {
const [isMenuActive, setIsMenuActive] = useState(false);
return (
<button className={`hamburger hamburger--slider ${isMenuActive && "is-active"}`} type="button" onClick={() => setIsMenuActive(!isMenuActive)}>
<span className="hamburger-box">
<span className="hamburger-inner"></span>
</span>
</button>
);
};
export default MenuButton;
``
You are starting the state with false value. So it's not firing the onClick event because it's inactive from the get go
change the initial state useState(true)
Ok I found the problem.
I didn't noticed that I was using React v17 (beta). I downgraded to React 16 and my button works well !
This is my React code:
<button
className="show-all"
onClick={() => { console.log("button clicked");}}>
button
</button>
This is what rendered in the browser:
<button class="show-all">button</button>
I am so curious: Why is the onclick missing? This will not affect the function, but I just cannot see the onclick name.
The following code has the same problem.
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
function shoot(){
console.log("shoot")
}
function handleClick(e) {
e.preventDefault();
console.log('The link was clicked.');
}
class ShowAlert extends Component {
showAlert() {
alert("I'm an alert");
}
render() {
return <button onClick={this.showAlert}>show alert</button>;
}
}
ReactDOM.render(
<>
<button onClick={() => console.log("good")}>
Click 1
</button>
<button onClick={shoot}>
Click 2
</button>
<button onClick={handleClick}>
Click 3
</button>
<ShowAlert />
</>
,
document.getElementById('root')
);
And I don't know if this small uncomfortable point is worth discussion.
React implements a synthetic events system that brings consistency and high performance to React apps and interfaces. It achieves consistency by normalizing events so that they have the same properties across different browsers and platforms.
A synthetic event is a cross-browser wrapper around the browser’s native event. It has the same interface as the browser’s native event, including stopPropagation() and preventDefault(), except the events work identically across all browsers.
It achieves high performance by automatically using event delegation. In actuality, React doesn’t attach event handlers to the nodes themselves. Instead, a single event listener is attached to the root of the document. When an event is fired, React maps it to the appropriate component element.
Resource - https://blog.logrocket.com/a-guide-to-react-onclick-event-handlers-d411943b14dd/
As pointed out in the comments to the question and the previous answer, React does not render events in the DOM, so they are not shown in the HTML elements.
I would like to add that if you just want to inspect the React events you can use devtools for that.
For example, for Firefox, MDN provides nice instructions on how to inspect events in devtools, and here is an example for Chrome.
This feature is what I like most, unlike Angular. This is not just about listeners, but also props. React handles the DOM virtually, so everything works virtually than having them in real DOM.
I had the same question in previous days and I noted: why is it so? Just continue reading for what I found specific in React.
You might also surprise why className renders class in the HTML? I mean, you might confuse why class is shown, but not onclick?
In JavaScript, class conflicts with the keyword class and it has a different name, i.e., className. React JSX just works like JavaScript and it binding the class in HTML.
Similar to className, there is htmlFor to the for attribute. You can see for in the rendered HTML like you see class for className.
So, when a React element is rendered in the browser it will only show the HTML attributes, but not React props.
There is onclick in JavaScript and onClick is specific to React (however, React internally transforms it to onclick as pointed out in other answer - synthetic event) and thus onClick is not shown in the DOM when it renders. React updates and works in a virtual DOM.
The only thing you need to note that - do provided props match a DOM attribute case sensitively? If yes, it will show in rendered HTML. Otherwise, No.
I hope, you have now a better understanding about these.
If you would like to see attached listener and props, etc. then you can use React devtools.
So, I'm trying to use Semantic UI modal component with the form component.
My problem is that if I use these two together the UI becomes bad.
I created a sandbox about my current situation: https://codesandbox.io/s/2n1pj96ry
As you can see now the submit button does not attached to the form.
If I move the Form component directly inside the Modal component, like this:
<Modal...>
<Form>
...
</Form>
</Modal>
the submit will attached to the form, but the UI breakes down.
I tried to add different classes to these components (like ui modal to the Form component, but it doesnt worked well).
Do you have any suggetsion?
Thanks for you help!
You can use the as prop on the Modal to make it a form element.
<Modal
as={Form}
onSubmit={e => handleSubmit(e)}
open={true}
size="tiny">
Any button with the submit type in your modal will fire the onSubmit handler. I find this to be a nice way to opt-in to required fields and easy validation by the browser on form elements.
Be sure to pass the event to your submit handler and use the preventDefault method to avoid the browser from automatically trying to post your form.
Forked your sandbox and made a working example. The modal is changed to a <form> element, the Input has the required property and the browser will demand the element is valid before firing the onSubmit handler. The default form action is prevented, and you can handle as desired with whatever.