Does anyone know how to trigger an event whenever a reactnative app is opened? eg. to refresh data whenever a user opens the app again.
Figured it out.
Need to use this. https://facebook.github.io/react-native/docs/appstateios.html#content
Go to that file where navigation starts from.
import React, { Component } from 'react';
import { Root } from './config/router';
class Index extends Component {
componentWillMount(){
//your event function code
}
render() {
return <Root />;
}
}
export default Index;
Here Root contains all screens where navigation starts.
Related
I have recently started to use React for specific parts of my custom JavaScript application. It is going well, but I don't quite understand how I can "unmount" or "stop rendering" or "clean up" a React component when I no longer need it?
Consider the following example of opening a modal that is a React component. How do I then close it and clean up the React side of things properly?
MyApp.js (JavaScript only, no React)
import { renderReactModal } from "./ReactModal.jsx";
class MyApp {
// I call this when I want to show my React component
openReactModal() {
// Create an empty div and append it to the DOM
this.modalDomElem = document.createElement("div");
document.append(this.modalDomElem);
// Render the React component into the div
renderReactModal(this.modalDomElem);
}
// I call this method when I want to hide my React component
closeReactModal() {
// Is it enough to do this to unmount / stop the React component from rendering?
// Or is there any other React-specific clean-up code required?
this.modalDomElem.remove();
}
}
ReactModal.jsx (React goes here)
import React from "react";
import ReactDOM from "react-dom";
class ReactModal extends React.Component {
render() {
return <h2>React Modal</h2>
}
}
export const renderReactModal = (domElem) => {
// NB: This syntax is for React 16 (different in 18).
ReactDOM.render(
<ReactModal />,
domElem
);
}
I searched some more and eventually found my way to this section of the React Docs: https://reactjs.org/docs/react-dom.html#unmountcomponentatnode
It seems that using ReactDOM.unmountComponentAtNode(container) is the recommended way to achieve this:
Remove a mounted React component from the DOM and clean up its event handlers and state.
Using that idea, I can change my initial code as follows.
MyApp.js (JavaScript only, no React)
import { mountReactModal, unmountReactModal } from "./ReactModal.jsx";
class MyApp {
// I call this method when I want to show my React component
openReactModal() {
// Create an empty div and append it to the DOM
this.modalDomElem = document.createElement("div");
document.append(this.modalDomElem);
// Mount the React component into the div
// NB: This causes the React component to render
mountReactModal(this.modalDomElem);
}
// I call this method when I want to hide my React component
closeReactModal() {
// Unmount the React component from the div
// NB: This cleans up the React component's event handlers and state
unmountReactModal(this.modalDomElement);
// Remove the div from the DOM
this.modalDomElem.remove();
}
}
ReactModal.jsx (React goes here)
import React from "react";
import ReactDOM from "react-dom";
class ReactModal extends React.Component {
render() {
return <h2>React Modal</h2>
}
}
// Mount
export const mountReactModal = (domElem) => {
// NB: This syntax is for React 16 (different in 18).
ReactDOM.render(
<ReactModal />,
domElem
);
}
// Unmount
export const unmountReactModal = (domElem) => {
// NB: This syntax is for React 16 (different in 18).
ReactDOM.unmountComponentAtNode(domElem);
}
I've started to code my first React app and it's awesome, but I can't figure out how to manage css files per-component(so the actual CSS won't load if it is not necessary).
React with webpack(correct me if I'm wrong please) wraps the project in such a way that at every given moment the app loads only what it needs(in terms of JS).
So if I have my main App component with only two buttons visible: btn-01 and btn-02, and inside of this component I have another two: component-01 and component-02, and they are hidden till the corresponded button is clicked(btn-01 for component-01), these components won't be loaded until the actual button is clicked(am I getting this right?), however this is not the same with css as I can tell, because I see the css of each of these(component-01 and component-02) components loaded right away the App is loaded, even though none of the buttons are clicked.
I'm not a big fan of inline styling, but I did test it with css module, but the result is the same in this aspect. So I'm not even sure if this is possible to implement in an easy way.
Here's a code, so perhaps I'm not implementing it correctly, but please don't mind the none-DRY code etc.
So as you may see, the style of Component-01 and -02 are loaded even though there is no need for them at the moment(none of the button is pressed).
App.js
import React, { Component } from "react";
import "./App.css";
import Component_01 from "./Component-01/Component-01";
import Component_02 from "./Component-02/Component-02";
class App extends Component {
state = {
isComponent_01: false,
isComponent_02: false,
};
toggleComponent01 = () => {
this.setState({
isComponent_01: !this.state.isComponent_01,
});
};
toggleComponent02 = () => {
this.setState({
isComponent_02: !this.state.isComponent_02,
});
};
render() {
let showComponent_01 = null;
if (this.state.isComponent_01) {
showComponent_01 = <Component_01 />;
}
let showComponent_02 = null;
if (this.state.isComponent_02) {
showComponent_02 = <Component_02 />;
}
return (
<div className="App">
<button className="btn-01" onClick={this.toggleComponent01}>
Btn-01
</button>
<button className="btn-02" onClick={this.toggleComponent02}>
Btn-02
</button>
{showComponent_01}
{showComponent_02}
</div>
);
}
}
export default App;
Component-01.js (and Component-02.js, just with -02.js)
import React from "react";
import style from "./Component-01.module.css";
function App() {
return <div className={style["component-01"]}>Component-01</div>;
}
export default App;
I'm trying to create an automatic slideshow in react, using react-slideshow. I'm very new to react and have just begun. I got this code from here.
import React from 'react';
import { Fade } from 'react-slideshow-image';
const images = [
'./img/p1.png',
'./img/p1.png',
'./img/p1.png'
];
const Slideshow = () => {
return (
<Fade
images={images}
duration="5000"
transitionDuration="1000"/>
)
}
What I am not getting is how to make this slideshow actually render. What I have done is called this function from inside a component in the same file i.e.
class App extends Component {
render() {
return (
<div className="App">
{Slideshow();}
</div>
);
}
}
export default App;
This is not rendering any slideshow or image, about which I'm not too surprised. The function is running. I console logged something and it got logged on the console. The rest of the page (I have other divs not shown here) is rendered and there is no error thrown. How to make this work?
Nothing seems wrong in this code.
try defining Slideshow() function inside app component.
make a call like "{ this.Slideshow }".
Check by removing "./" in image path. (Try..)
Also check the path of image. Sometime they refer to public folder outside the src folder. maybe public/images/img.png
Slideshow is a React component, so you need to render it using JSX, not invoke the function:
class App extends Component {
render() {
return (
<div className="App">
<Slideshow/>
</div>
);
}
}
export default App;
Want to trigger an alert or console log before the user navigates to a new domain. From the docs, setRouteLeaveHook or onLeave should work. I followed these directions.
import React from 'react'
import { withRouter } from 'react-router'
const Page = withRouter(
React.createClass({
componentDidMount() {
this.props.router.setRouteLeaveHook(this.props.route, this.routerWillLeave)
},
routerWillLeave(nextLocation) {
console.log("Moved to different domain");
return 'Your work is not saved! Are you sure you want to leave?'
},
render() {
return Redirect
}
})
)
export default Page
Page is the top level component in my app. Using react-router v3 with redux.
How can I trigger an alert before the user leaves our site?
Add the withRouter HOC wrapper on your export like this:
export default withRouter(Page);
Using Mobx, after updating the store (i.e. clicking the button) the component does not re-render. I've installed mobx devtools which shows nothing after the initial load, and there is no error in the console. Any ideas what I've done wrong?
Store.js:
import { observable } from 'mobx';
class Store {
#observable me;
constructor() {
this.me = 'hello';
}
change_me(){
this.me = 'test 1234';
}
}
export default Store;
layout.js:
import React from "react";
import { observer } from 'mobx-react';
#observer
export default class Layout extends React.Component{
render(){
return(
<div>
<h1>{this.props.store.me}</h1>
<button onClick={this.on_change}>Change</button>
</div>
)
}
on_change = () => {
this.props.store.change_me();
}
}
index.js:
import React from "react";
import ReactDOM from "react-dom";
import Layout from "./components/Layout";
import Store from "./Store";
import DevTools, { configureDevtool } from 'mobx-react-devtools';
// Any configurations are optional
configureDevtool({
// Turn on logging changes button programmatically:
logEnabled: true,
// Turn off displaying conponents' updates button programmatically:
updatesEnabled: false,
// Log only changes of type `reaction`
// (only affects top-level messages in console, not inside groups)
logFilter: change => change.type === 'reaction',
});
const app = document.getElementById('app');
const store = new Store();
ReactDOM.render(
<div>
<Layout store={store} />
<DevTools />
</div>
, app);
I would start by adding #action to your change_me() function. From what I understand, it's not always completely required, but I have encountered problems like this in my own code several times when I've forgotten to add it.
Additionally post your .babelrc as #mweststrate suggested, as it will help others to check that the proper plugins are loaded.
Just add makeObservable(this); in constructor function like below
constructor() {
makeObservable(this);
}
My guess would be to have uninitialized #observable. It is very counter-intuitive, but Babel doesn't handle those well. Even adding #observable me = undefined might help (see the generated js code when you assign something there. Generally I'd remove constructor completely and move the initialization to declaration (i.e. #observable me = "hello" an no constructor). It should then work fine.
Watch the binding of the this context.
<button onClick={this.on_change}>Change</button>
the this reference will not be to the class, so likely when you are actually clicking it is going to say something along the lines of no props on undefined. Changing to:
<button onClick={this.on_change.bind(this)}>Change</button>
should fix it. Or better yet, bind the context in the constructor so its not re-binding on every render
constructor(props) {
super(props)
this.on_change = this.on_change.bind(this)
}
then you can go back to your