Setting focus via a ref only works in setTimeout in React? - reactjs

My code below works but the this.buttonRef.current.firstChild.focus() stops working if it's not in a setTimeout function.
From looking at the official docs for refs I cant see why this is happening. Is there anything obviously wrong with my component? If not Im wondering if another component on my site is 'stealing' focus as when the url prop changes a modal is closed.
UPDATE: One weird thing is if I console.log outside of the setTimeout then I can see the element is present in the DOM.
UPDATE2: Turns out it was React Trap Focus in my modal that was causing the issue. Removing the focus trap means I don't need the timeout. As I need the focus trap I think the setTimeout will need to stay.
https://github.com/davidtheclark/focus-trap-react
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.buttonRef = React.createRef();
}
componentDidUpdate(prevProps) {
if (this.props.url === '' && prevProps.url = "old-url") {
console.log('target element: ', this.buttonRef.current.firstChild)
// This doenst work if not in a setTimeout
// this.buttonRef.current.firstChild.focus();
setTimeout(() => {
this.buttonRef.current.firstChild.focus();
}, 1);
}
}
render() {
const {
limitIsReached,
add
} = this.props;
return (
<Fragment>
<Title>My title</Title>
<Section>
<Button>
Add a promo code
</Button>
<span ref={this.buttonRef}>
{limitIsReached ? (
<Alert
message="Sorry limit reached"
/>
) : (
<Button
onClick={add}
>
Add new
</Button>
)}
</span>
<List compact />
</Section>
</Fragment>
);
}
}
export default MyComponent;

Considering that seemingly componentDidUpdate runs before your buttonRef is resolved, a short setTimeout isn't the worst solution.
You could try other ways involving setting state:
componentDidUpdate(prevProps) {
if (.... oldurl) {
this.setState({focusBtn: true})
}
Then when the buttonref resolves:
<span ref={ref=>{
if (this.state.focusBtn) {
this.buttonRef = ref;
this.buttonRef.current.firstChild.focus();
} } >...
EDIT
ok so if you remove the conditional in your render method, React will ensure that your ref has resolved on componentDidMount and also componentDidUpdate (as you wish it to be)
Try this:
<span ref={this.buttonRef}>
<Alert
message="Sorry limit reached"
style={{display: limitIsReached ? 'block' : 'none'}}
/>
<Button
onClick={add} style={{display: limitIsReached ? 'none' : 'inline-block'}}
>
Add new
</Button>
)}
</span>

Related

React: Setting and updating based on props

Currently I am facing the problem that I want to change a state of a child component in React as soon as a prop is initialized or changed with a certain value. If I solve this with a simple if-query, then of course I get an infinite loop, since the components are then rendered over and over again.
Component (parent):
function App() {
const [activeSlide, setActiveSlide] = useState(0);
function changeSlide(index) {
setActiveSlide(index);
}
return (
<div className="app">
<div className="app__nav">
<Button icon="FiSun" handler={changeSlide} active={activeSlide} index="0" />
<Button icon="FiSettings" handler={changeSlide} active={activeSlide} index="1" />
</div>
</div>
);
}
Component (child):
function Button(props) {
const Icon = Icons[props.icon];
const [activeClass, setActiveClass] = useState("");
// This attempts an endless loop
if(props.active == props.index) {
setActiveClass("active");
}
function toggleView(e) {
e.preventDefault();
props.handler(props.index);
}
return(
<button className={activeClass} data-index={props.index} onClick={toggleView}>
<Icon />
</button>
)
}
Is there a sensible and simple approach here? My idea would be to write the if-query into the return() and thus generate two different outputs, even though I would actually like to avoid this
The React docs have a nice checklist here used to determine if something does or does not belong in state. Here is the list:
Is it passed in from a parent via props? If so, it probably isn’t state.
Does it remain unchanged over time? If so, it probably isn’t state.
Can you compute it based on any other state or props in your component? If so, it isn’t state.
The active class does not meet that criteria and should instead be computed when needed instead of put in state.
return(
<button className={props.active == props.index ? 'active' : ''} data-index={props.index} onClick={toggleView}>
<Icon />
</button>
)
This is a great use of useEffect.
instead of the if statement you can replace that with;
const {active, index} = props
useEffect(_ => {
if(active == index) {
setActiveClass("active");
}
}, [active])
The last item in the function is a dependency, so useEffect will only run if the active prop has changed.
React automatically re-renders a component when there is a change in the state or props. If you're just using activeClass to manage the className, you can move the condition in the className as like this and get rid of the state.
<button className={props.active === props.index ? 'active' : ''} data-index={props.index} onClick={toggleView}>
<Icon />
</button>
however, if you still want to use state in the child component, you can use the useEffect hook to to update the state in the child component.
Try to use the hook useEffect to prevent the infinite loop. (https://fr.reactjs.org/docs/hooks-effect.html)
Or useCallback hook. (https://fr.reactjs.org/docs/hooks-reference.html#usecallback)
Try this and tell me if it's right for you :
function App() {
const [activeSlide, setActiveSlide] = useState(0);
const changeSlide = useCallback(() => {
setActiveSlide(index);
}, [index]);
return (
<div className="app">
<div className="app__nav">
<Button icon="FiSun" handler={changeSlide} active={activeSlide} index="0" />
<Button icon="FiSettings" handler={changeSlide} active={activeSlide} index="1" />
</div>
</div>
);
}

setState second argument callback function alternative in state hooks

I made a code sandbox example for my problem: https://codesandbox.io/s/react-form-submit-problem-qn0de. Please try to click the "+"/"-" button on both Function Example and Class Example and you'll see the difference. On the Function Example, we always get the previous value while submitting.
I'll explain details about this example below.
We have a react component like this
function Counter(props) {
return (
<>
<button type="button" onClick={() => props.onChange(props.value - 1)}>
-
</button>
{props.value}
<button type="button" onClick={() => props.onChange(props.value + 1)}>
+
</button>
<input type="hidden" name={props.name} value={props.value} />
</>
);
}
It contains two buttons and a numeric value. User can press the '+' and '-' button to change the number. It also renders an input element so we can use it in a <form>.
This is how we use it
class ClassExample extends React.Component {
constructor(props) {
super(props);
this.state = {
value: 1,
lastSubmittedQueryString: ""
};
this.formEl = React.createRef();
}
handleSumit = () => {
if (this.formEl.current) {
const formData = new FormData(this.formEl.current);
const search = new URLSearchParams(formData);
const queryString = search.toString();
this.setState({
lastSubmittedQueryString: queryString
});
}
};
render() {
return (
<div className="App">
<h1>Class Example</h1>
<form
onSubmit={event => {
event.preventDefault();
this.handleSumit();
}}
ref={ref => {
this.formEl.current = ref;
}}
>
<Counter
name="test"
value={this.state.value}
onChange={newValue => {
this.setState({ value: newValue }, () => {
this.handleSumit();
});
}}
/>
<button type="submit">submit</button>
<br />
lastSubmittedQueryString: {this.state.lastSubmittedQueryString}
</form>
</div>
);
}
}
We render our <Counter> component in a <form>, and want to submit this form right after we change the value of <Counter>. However, on the onChange event, if we just do
onChange={newValue => {
this.setState({ value: newValue });
this.handleSubmit();
}}
then we won't get the updated value, probably because React doesn't run setState synchronously. So instead we put this.handleSubmit() in the second argument callback of setState to make sure it is executed after the state has been updated.
But in the Function Example, as far as I know in state hooks there's nothing like the second argument callback function of setState. So we cannot achieve the same goal. We found out two workarounds but we are not satisfied with either of them.
Workaround 1
We tried to use the effect hook to listen when the value has been changed, we submit our form.
React.useEffect(() => {
handleSubmit();
}, [value])
But sometimes we need to just change the value without submitting the form, we want to invoke the submit event only when we change the value by clicking the button, so we think it should be put in the button's onChange event.
Workaround 2
onChange={newValue => {
setValue(newValue);
setTimeout(() => {
handleSubmit();
})
}}
This works fine. We can always get the updated value. But the problem is we don't understand how and why it works, and we never see people write code in this way. We are afraid if the code would be broken with the future React updates.
Sorry for the looooooooong post and thanks for reading my story. Here are my questions:
How about Workaround 1 and 2? Is there any 'best solution' for the Function Example?
Is there anything we are doing wrong? For example maybe we shouldn't use the hidden input for form submitting at all?
Any idea will be appreciated :)
Can you call this.handleSubmit() in componentDidUpdate()?
Since your counter is binded to the value state, it should re-render if there's a state change.
componentDidUpdate(prevProps, prevState) {
if (this.state.value !== prevState.value) {
this.handleSubmit();
}
}
This ensure the submit is triggered only when the value state change (after setState is done)
It's been a while. After reading React 18's update detail, I realize the difference is caused by React automatically batching state updates in function components, and the "official" way to get rid of it is to use ReactDOM.flushSync().
import { flushSync } from "react-dom";
onChange={newValue => {
flushSync(() => {
setValue(newValue)
});
flushSync(() => {
handleSubmit();
});
}}

React - onClick event not working correctly

I'm attempting to pass an onClick function as a prop to a child component in React. However, nothing is being logged to the console when the button is clicked. For now I'm just trying to console log to make sure the event is actually firing.
Any Ideas?
class App extends React.Component {
togglePallets = (pallet) => {
console.log('test');
}
render() {
return (
<div className="mainWrapper">
<div className="mainContainer">
<div>
<img src="images/picture-of-me.jpg" alt="Me"></img>
</div>
</div>
<SideBar toggle={this.togglePallets} showPallets={[this.state.showAboutPallet, this.state.showLanguagesPallet,
this.state.showProjectsPallet, this.state.showContactPallet]}/>
{this.state.showAboutPallet && <AboutPallet />}
{this.state.showAboutPallet && <LanguagesPallet />}
{this.state.showAboutPallet && <ProjectsPallet />}
{this.state.showAboutPallet && <ContactPallet />}
</div>
);
}
}
function SideBar(props) {
return (
<div className="sideBarContainer">
<Button icon={faUser} showAboutPallet={props.showPallets[0]} onClick={props.toggle}/>
</div>
);
}
What you have written is correct. But we can try it in another way using an arrow function.
onClick={(e) => props.toggle(e,data)}
And, make relevant changes in toggle function, so it may support multiple arguments.
Change your togglePallets to any of the below
togglePallets() {
console.log("test");
};
If you want to access event then
togglePallets(event) {
console.log("test");
};
Or
togglePallets=event =>{
console.log("teeventst");
};

Error 'ref is not a prop' when using ref on a div inside of a react component

So the main aim of me using refs is so that I can reset the scroll position of a scrollable div, this is an image of the div before adding content this is how it looks before dynamically adding divs to the scrollable container div
This is a screenshot of the div after adding boxes to it:
the box is created outside of viewport and is created at the top of the scrollable area
So to be able to maintain the viewport at the top of the scrollable area I am hoping to use refs to do ReactDOM.findDOMNode(this.songIdWrapper) and then manipulate the scrollTop or use scrollTo methods.
Please find the code snippet below:
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
class AddPlaylist extends Component {
constructor(props){
super(props);
this.state = {
displaySearch: false,
id: '',
playlistName:'',
playlistTitle:'',
songs:[]
}
this.handleIdSubmit = this.handleIdSubmit.bind(this);
this.handleIdChange = this.handleIdChange.bind(this);
this.handleNamechange = this.handleNamechange.bind(this);
this.handleNameSubmit= this.handleNameSubmit.bind(this);
this.callback=this.callback.bind(this);
}
componentWillUpdate () {
console.log(ReactDOM.findDOMNode(this.songIdWrapper));
}
componentDidUpdate () {
}
callback (songId) {
this.songIdWrapper=songId;
}
render () {
return(
<div className='add-playlist-wrapper'>
<div className='form-wrapper container'>
<form onSubmit={this.handleNameSubmit} className='playlist-name-wrapper'>
<input className={this.state.submittedName ? 'hide-input' : ''} required onChange={this.handleNamechange} value={this.state.playlistName} placeholder='Playlist title'/>
{this.state.submittedName ? <p className='title'>{this.state.playlistTitle}</p> : null}
</form>
<form onSubmit={this.handleIdSubmit} className='add-id-wrapper'>
<div className='input-add-playlist'>
<input required onChange={this.handleIdChange} value={this.state.id} placeholder='Add song...'/>
<button type='submit' className='fabutton'>
<i className="add-button fa fa-plus-square-o fa-3x" aria-hidden="true"></i>
</button>
</div>
</form>
<div id='song-id-wrapper' ref={this.callback}>
{this.state.songs.map((song, i) => {
return (<div key={i} className='song'>
<p>{song}</p>
</div>
)
})}
</div>
</div>
</div>
)
}
handleIdSubmit (event) {
event.preventDefault();
const newState = this.state.songs.slice();
newState.push(this.state.id);
this.setState({
songs:newState
})
}
handleIdChange (event) {
this.setState({
id: event.target.value
})
}
handleNamechange (event) {
this.setState({
playlistName: event.target.value
})
}
handleNameSubmit (event) {
event.preventDefault();
this.setState({
playlistTitle: this.state.playlistName
})
}
}
export default AddPlaylist;
The error message I get is:
this is the error message stating that ref is not a prop
So I am quite new to react and as far as I'm aware this is an attribute on a div element not passed as a prop to a component. So I hope you can see my confusion as when I search google/stack-overflow I see a lot of comments relating to child components. I am fully aware string refs have been depreciated and that callbacks should be used but no matter what I try I cannot get rid of this error message.
Any help would be greatly appreciated.
I guess the issue is that you try to access the ref in the componentWillUpdate Hook. Because from the pure setup there is nothing wrong.
The componentWillUpdate Hook gets actually called before the next render cycle, which means you access the ref BEFORE your component gets rendered, which means that you always access the ref from the render cycle before. The ref gets updated with the next render cycle.
https://developmentarc.gitbooks.io/react-indepth/content/life_cycle/update/tapping_into_componentwillupdate.html
I think you should do the scroll position handling AFTER the component did update, not before it will update!

In React, Is it good practice to search for certain element in DOM?

Is it good to just specify className for element so i could find it later in the DOM through getElementsByClassName for manipulations?
Adding a class to find the DOM element? Sure you can do that, but refs are probably the better solution.
Manipulating the DOM element? That's an absolute no-go. The part of the DOM that is managed by React should not be manipulated my anything else but React itself.
If you come from jQuery background, or something similar, you will have the tendency to manipulate element directly as such:
<div class="notification">You have an error</div>
.notification {
display: none;
color: red;
}
.show {
display: block;
}
handleButtonClick(e) {
$('.notification').addClass('show');
}
In React, you achieve this by declaring what your elements (components) should do in different states of the app.
const Notification = ({ error }) => {
return error
? <div className="notification">You have an error</div>
: null;
}
class Parent extends React.Component {
state = { error: false };
render() {
return (
<div>
<Notification error={this.state.error} />
<button onClick={() => this.setState({ error: true })}>
Click Me
</button>
}
}
The code above isn't tested, but should give you the general idea.
By default, the state of error in Parent is false. In that state, Notification will not render anything. If the button is clicked, error will be true. In that state, Notification will render the div.
Try to think declaratively instead of imperatively.
Hope that helps.
When using React, you should think about how you can use state to control how components render. this.setState performs a rerender, which means you can control how elements are rendered by changing this.state. Here's a small example. I use this.state.show as a boolean to change the opacity of the HTML element.
constructor(props) {
super(props)
this.state = {
show: true
}
}
handleClick() {
this.setState({show: false})
}
render() {
const visibility = this.state.show ? 1 : 0
return (
<button style={{opacity: visibility} onClick={() => this.handleClick()}>
Click to make this button invisible
</button>
)
}

Resources