React Lazyload as soon as page interacted with - javascript

I'm building a React site which uses live chat and am using the react-livechat package. I've paired this up with the react-lazyload plugin to try to prevent it from adversely affect page load times.
I'm now trying to work out a way to load the livechat component in as soon as the page is interacted with. Currently it only renders when the page is scrolled to within a set distance of the component which by default is the footer of the page. This does prevent the page load being impacted but requires a user to scroll a certain distance before the component loads. Ideally it would load form any interaction with the page.
import React, { Component } from 'react';
import LiveChat from 'react-livechat';
import LazyLoad from 'react-lazyload';
class App extends Component {
render() {
return (
<div className="App">
...
<LazyLoad once>
<LiveChat license={'xxxxxx'} />
</LazyLoad>
...
</div>
);
};
}
export default App;

I managed to get this behavior with a workaround and loading the component after a certain period of time. I found that 10 seconds worked well to ensure even on mobile everything had entirely rendered.
// App.js
import React, { Component } from 'react';
import LazyLiveChat from './components/utils/lazyLiveChat';
class App extends Component {
constructor() {
super();
this.state = { loadLiveChat: false };
}
componentDidMount() {
setTimeout(() => this.setState({loadLiveChat: true}), 10000);
}
render() {
return (
<div className="App">
...
<LazyLiveChat loadChat={this.state.loadLiveChat} />
...
</div>
);
};
}
export default App;
// lazyLiveChat.js
import React, { Component } from 'react';
import LiveChat from 'react-livechat';
class LazyLiveChat extends Component {
render() {
if (this.props.loadChat) {
return (
<LiveChat license={xxxxxx} />
);
}
return null;
}
}
export default LazyLiveChat;

Related

Console.Log Not Being Called Inside React Constructor

I'm trying to add a component to a default .NET Core MVC with React project. I believe I have everything wired up to mirror the existing "Fetch Data" component, but it doesn't seem like it's actually being called (but the link to the component in my navbar does move to a new page).
The component itself...
import React, { Component } from 'react';
export class TestComponent extends Component {
static displayName = TestComponent.name;
constructor (props) {
super(props);
console.log("WHO NOW?");
this.state = { message: '', loading: true, promise: null };
this.state.promise = fetch('api/SampleData/ManyHotDogs');
console.log(this.state.promise);
}
static renderForecastsTable (message) {
return (
<h1>
Current Message: {message}
</h1>
);
}
render () {
let contents = this.state.loading
? <p><em>Loading...</em></p>
: TestComponent.renderForecastsTable(this.state.message);
return (
<div>
<h1>Weather forecast</h1>
<p>This component demonstrates fetching data from the server.</p>
{contents}
</div>
);
}
}
The App.js
import React, { Component } from 'react';
import { Route } from 'react-router';
import { Layout } from './components/Layout';
import { Home } from './components/Home';
import { FetchData } from './components/FetchData';
import { Counter } from './components/Counter';
import { TestComponent } from './components/TestComponent';
export default class App extends Component {
static displayName = App.name;
render () {
return (
<Layout>
<Route exact path='/' component={Home} />
<Route path='/counter' component={Counter} />
<Route path='/fetch-data' component={FetchData} />
<Route path='/test-controller' component={TestComponent} />
</Layout>
);
}
}
That console.log("Who now") is never called when I inspect, and the page remains totally blank. I can't find a key difference between this and the functioning components, and google has not been much help either. Any ideas what is missing?
Edit
While troubleshooting this, I ended up creating a dependency nightmare that broke the app. Since I'm only using the app to explore React, I nuked it and started over--and on the second attempt I have not been able to reproduce the not-rendering issue.
It is advisable to use componentDidMount to make the call to the REST API with the fetch or axios.
class TestComponent extends Component{
constructor(props){
state = {promise: ''}
}
async componentDidMount () {
let promise = await fetch ('api / SampleData / ManyHotDogs');
this.setState ({promise});
console.log (promise);
}
render(){
return(
<div>{this.state.promise}</div>
);
}
}

Render a new Component without using router

I've created an application to React, and when it starts, the App component is rendered. I would like that when the user clicks on a button or link, the button or link has to be in the App component when clicking on that link, another component will be rendered but not inside the App component but only the new component will be rendered in the same URL. As for this new component, it has to have a similar button so that when the user clicks, only the App component is rendered and this component that the user has clicked on is not rendered, only the App component.
I do not know if I explained myself correctly. Ask me any question if you need some clarification.
My App component is the following:
import React, { Component } from 'react';
import Touch from './Touch';
import '../App.css';
class App extends Component{
render() {
return(
<div>
<div className="wrapper" >
<button >NewComponent</button><NewComponent />???
<h1>Google Cloud Speech with Socket.io</h1>
<p id="ResultText"><span className="greyText">No Speech to Text yet</span></p>
</div>
<div className="buttonWrapper" >
<button className="btn" id="startRecButton" type="button"> Start recording</button>
<button className="btn" id="stopRecButton" type="button"> Stop recording</button>
</div>
</div>
);
}
}
export default App
My index.js is the following:
import React from 'react';
import ReactDOM from 'react-dom';
import './App.css';
import App from './components/App.js';
import registerServiceWorker from './registerServiceWorker';
ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();
If you really don't want to use react-router you will need to store a value in the component's state and change the rendering method to reflect which button was pressed. If you want each of those component to include the button you need to switch, do the following :
class App extends Component {
constructor(props){
super(props);
this.state = {renderA: false,};
}
handleClick = (event) => {
this.setState((prevState) => ({renderA: !prevState.renderA}));
};
render = () => {
return(
<div>
{this.state.renderA ?
<ComponentA handleClick={this.handleCLick}/>:
<ComponentB handleClick={this.handleCLick}/>
}
</div>
);
};
} export default App;
// ComponentA
class ComponentA extends Component {
render = () => {
return(
<div>
// what you want inside your first page here
<button onClick={this.props.handleClick}
</div>
);
}
} export default ComponentA;
// ComponentB
class ComponentB extends Component {
render = () => {
return(
<div>
// what you want inside your second page here
<button onClick={this.props.handleClick}
</div>
);
}
} export default ComponentB;
But using react-router might also suits your case, and if you are going to write a large app, you should use it instead of rendering differents children components within the same one, based on users inputs.
If the URL stay the same, I don't think React-Router might help you.
If you want that App Component is not loaded, I think you should create two more Component, a Wrapper one, and the new component you want to display (from now on newComponent). What I suggest is:
Creating a property isButtonClicked inside the state of the Wrapper Component;
Creating a function handleButtonClick() inside the Wrapper Component:
handleButtonClick() => {
let isButtonClicked = !this.state.isButtonClicked;
this.setState({ isButtonClicked });
}
In the render() method of the Wrapper component, you write something like this:
render() {
if (this.state.isButtonClicked)
return <App />
else
return <NewComponent />
}
Then, in both App and NewComponent, if you click on the button, you call the this.props.handleButtonClick(), which will lead to a change of the state of Wrapper Component, therefore to a change of what is shown on the screen.

React Uncaught DOMException: Failed to execute 'createElement' on 'Document': The tag name provided ('<div>') is not a valid name

In react applications, we always have a root component and everything else is a child of that component.
So what I decided to do is break that convention whenever I am going to display a modal, and create a new element or a new component and append it directly to document.body.
a child of body we will not have anymore stacking z-index issues, so this modal will always show up 100% of the time. Or at least that was my thinking.
So I made a new component called modal.js
Inside of this modal, rather than returning a div with some fancy css styling on its children I am just going to return a no script tag which means don’t render anything like so:
import React, { Component } from 'react';
import ReactDOM from ‘react-dom’;
class Modal extends Component {
render() {
return <noscript />;
}
}
export default Modal;
So when I display the modal component its not going to display anything on the screen whatsoever. So then how do I get this modal on the screen then?
Well, I decided to do a bit of a workaround by adding in a componentDidMount() like so:
import React, { Component } from 'react';
import ReactDOM from ‘react-don’;
class Modal extends Component {
componentDidMount() {
}
render() {
return <noscript />;
}
}
export default Modal;
So whenever this component gets mounted or rendered to the screen I am going to create a new div in memory and assign it to this.modalTarget like so:
import React, { Component } from 'react';
import ReactDOM from ‘react-don’;
class Modal extends Component {
componentDidMount() {
this.modalTarget = document.createElement(‘<div>’);
}
render() {
return <noscript />;
}
}
export default Modal;
Here is the finished file:
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
class Modal extends Component {
componentDidMount() {
this.modalTarget = document.createElement('<div>');
this.modalTarget.className = 'modal';
document.body.appendChild(this.modalTarget);
this._render();
}
componentWillUpdate() {
this._render();
}
componentWillUnmount() {
ReactDOM.unmountComponentAtNode(this.modalTarget);
document.body.removeChild(this.modalTarget);
}
_render() {
ReactDOM.render(<div>{this.props.children}</div>, this.modalTarget);
}
render() {
return <noscript />;
}
}
export default Modal;
I was expecting for this to work, maybe get an Inviolant error, but certain not:
Uncaught DOMException: Failed to execute 'createElement' on
'Document': The tag name provided ('<div>') is not a valid name.
I am not sure what is going on here.
A comment from Bravo helped me solve this. What helped me was refactoring this:
this.modalTarget = document.createElement('<div>');
to this:
this.modalTarget = document.createElement('div');
Why don't you use the React.Fragment?
You could do something like that...
const Modal = () => (
<React.Fragment>
<noscript />
</React.Fragment>
);
export default Modal;

Add loader on button click in react/redux application

I'm trying to add a Loader as Higher-Order-Component on button click in react/redux application.
Already have working Loader component and styling, just need to set logic when button is clicked show loader and hide existing button.
Button component:
import React from 'react'
import '../../../styles/components/_statement-print.scss';
import Loader from './Loader';
const StatementPrint = (props) => {
return (
<div>
<button
className="print-statement-button"
onClick={props.handleStatementPrint}>PRINT
</button>
</div>
);
};
export default Loader(StatementPrint);
Loader:
import React, { Component} from 'react';
import '../../../styles/components/_loader.scss';
const Loader = (WrappedComponent) => {
return class Loader extends Component {
render() {
return this.props.handleStatementPrint // Where must be logic when to show loader or existing button component
? <button className="loader-button">
<div className="loader">
<span className="loader-text">LOADING...</span>
</div>
</button>
: <WrappedComponent {...this.props} />
}
}
}
export default Loader;
In Loader component i added comment where need to write logic when to set loader or button.
I followed this example: ReactCasts - Higher Order Components
I searched a lot of examples but most of them shows how to set loader then is data is fetching, but in my case i just need to show then onClick method is triggered.
So how to set logic when onClick method is fired? Is this is a good aproach? Also it will be better to try acomplish this doing with redux state, but don't know how to do this.
Any help will be appreciated.
You will have to make small modifications to achieve what you want.
The wrapper component Loader can have a isLoading state, on the basis of which you can decide whether to show the loader span or the wrapped component.
This state isLoading can be updated by the wrapped component by passing showLoader function as a prop.
Button component
import React from 'react'
import '../../../styles/components/_statement-print.scss';
import Loader from './Loader';
const StatementPrint = ({handleStatementPrint, showLoader}) => {
return (
<div>
<button
className="print-statement-button"
onClick={() => {
showLoader();
handleStatementPrint();
}}>
PRINT
</button>
</div>
);
};
export default Loader(StatementPrint);
Loader
import React, { Component} from 'react';
import '../../../styles/components/_loader.scss';
const Loader = (WrappedComponent) => {
return class Loader extends Component {
constructor(props) {
super(props);
this.state = {
isLoading: false
}
this.showLoader = this.showLoader.bind(this);
}
showLoader() {
this.setState({isLoading: true});
}
render() {
return this.state.isLoading
? <button className="loader-button">
<div className="loader">
<span className="loader-text">LOADING...</span>
</div>
</button>
: <WrappedComponent
{...this.props}
showLoader={this.showLoader}
/>
}
}
}
export default Loader;
EDIT
Since handleStatementPrint was required to be called, I have updated the click handler to include that function.
Also using de-structuring to avoid typing props repeatedly. See here for more info.
Just some external state is needed.
If you can't have external state (eg isLoading) than you could pass a function into a loader hoc which will derive isLoading from current props
Example: https://codesandbox.io/s/8n08qoo3j2

Next.js Persistent component - Youtube embed that plays even after changing page

I am trying to create a Next.js react app. One of the requirements is that a youtube player must persist when changing pages. Only issue is that I'm not sure if it's possible with the way Next works. It seems that pages will aways re-mount regardless of the structure.
Here in my app I export Index into page.js which acts as a parent component.
<Media/> //Youtube player
page.js will always remount thus the player will reload.
page.js:
import React from 'react';
import { Provider } from 'react-redux';
import { checkLang } from '../helpers/langSupport';
import { changeLang } from '../store/actions/langAction';
import store from '../store/store';
import { Router } from '../config/router';
import Media from './youtube';
import Head from './head';
import Nav from './nav';
const childPage = (ChildPage) => {
return (
class Page extends React.Component {
componentDidMount(){
this.checkLanguage()
}
checkLanguage() {
checkLang(this.props.url, (status, result) => {
if(status){
store.dispatch(changeLang(result))
}else{
Router.pushRoute('/en'+this.props.url.asPath)
}
})
}
render() {
return (
<Provider store={store}>
<div>
<Head />
<Nav />
<ChildPage {...this.props} />
<Media/>
</div>
</Provider>
)
}
}
)
}
export default childPage;
index.js:
import React from 'react';
import { connect } from 'react-redux'
import { add, minus } from '../store/actions/countAction';
import Page from '../components/page';
export class Index extends React.Component {
render() {
return (
<div>
<div className="hero">
Count: {this.props.count.count}
<br/><br/>
<button onClick={()=>this.props.dispatch(add(1))}>Add</button>
<button onClick={()=>this.props.dispatch(minus(1))}>Minus</button>
</div>
<style jsx>{`
.hero{
margin-left: 50px;
}
`}</style>
</div>
)
}
}
export default Page(connect(state=>state)(Index));
This has now been implemented as _app.js. Check out the next.js readme to learn more.
Unfortunately this is something that does not exist in Next.js yet. Though it is actively discussed and will probably be implemented in the near future.
ReactDOM.render is called on every page change, so this is not possible today.
See discussions on:
https://github.com/zeit/next.js/issues/88
https://github.com/zeit/next.js/pull/2440
https://github.com/zeit/next.js/pull/3288

Categories

Resources