When you open reactjs.org, under "Declarative" header, there is a sentence: React will efficiently update and render just the right components when your data changes.
For a couple of my apps, I'm using the following structure: App | AppContainer(all the app logic, protected before login) | Login(Login form)
This structure works well if you return 2 different components inside App's render
, according to the user's credentials.
render(){
if(isUserLoggedIn()){
return <AppContainer />;
}
return <Login />;
}
Inside the Login
component, I'm refreshing the page with window.location.reload
so the App's render
will be triggered, and I'll get the AppContainer
component.
But it feels a little like jQuery + Angular. Is there a better (more React) way to trigger render function, or is this how things should be?
Is there a better(more React) way to trigger render function...
The usual way is to have state, in this case at minimum a boolean for whether the user is logged in, and update that state when the user logs in successfully or logs out. Updating state triggers rendering.
In your case, since you're using Redux, you'd probably have your state there.
I don't use Redux (yet?), this is vaguely what it would look like without, roughly (if you're using a class component as you seem to be):
class App extends Component {
constructor(props) {
super(props);
this.state = {
loggedIn: /*...initial value, perhaps from web storage or cookie...*/;
};
this.onLogin = this.onLogin.bind(this);
this.onLogout = this.onLogout.bind(this);
}
onLogin() {
// ...probably stuff here, then:
this.setState({loggedIn: true});
}
onLogout() {
// ...probably stuff here, then:
this.setState({loggedIn: false});
}
render() {
if (this.state.logedIn) {
return <AppComponent onLogout={this.onLogout}/>;
}
return <Login onLogin={this.onLogin}/>;
}
}
or with hooks:
const App = () => {
const [loggedIn, setLoggedIn] = useState(/*...initial value, perhaps from web storage or cookie...*/);
const onLogin = useCallback(() => {
// ...probably stuff here, then:
setLoggedIn(true);
}, [loggedIn]);
const onLogout = useCallback(() => {
// ...probably stuff here, then:
setLoggedIn(false);
}, [loggedIn]);
if (this.state.logedIn) {
return <AppComponent onLogout={onLogout}/>;
}
return <Login onLogin={onLogin}/>;
}
(again, roughly)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With