import React from "react";
import { render } from "react-dom";
import { createStore, applyMiddleware } from "redux";
import { Provider, connect } from "react-redux";
import thunk from "redux-thunk";
const disabled = (state = true, action) => {
return action.type === "TOGGLE" ? !state : state;
};
class Button extends React.Component {
componentDidUpdate(prevProps) {
if (prevProps.disabled !== this.props.disabled && !this.props.disabled) {
// this.ref.focus(); // uncomment this to see the desired effect
}
}
render() {
const { props } = this;
console.log("rendering", props.value);
return (
<div>
<input
type="checkbox"
onClick={() => {
props.toggle();
this.ref.focus(); // doesn't work
}}
/>
<input
disabled={props.disabled}
ref={ref => {
this.ref = ref;
}}
/>
</div>
);
}
}
const toggle = () => ({
type: "TOGGLE"
});
const A = connect(state => ({ disabled: state }), { toggle })(Button);
const App = () => (
<Provider store={createStore(disabled, applyMiddleware(thunk))}>
<A />
</Provider>
);
render(<App />, document.getElementById("root"));
I want to focus the input
when the checkbox is checked. However, this.ref.focus()
must be called only after the component re-renders with props.disabled === false
, as an input
with disabled
prop cannot be focused.
If I do the logic in componentDidUpdate
, I'm able to achieve what I want. But this is not a clean solution as the logic is specific to the onClick
handler rather than a lifecycle event.
Is there any other way to accomplish this? (preferably with a working codesandbox example)
from Redux-thunk dispatch an action and wait for re-render
No comments:
Post a Comment