#StackBounty: #css #reactjs #iphone #material-ui Device width and height in material-ui

Bounty: 50

I am trying to add the specific width and height of (Iphone 7 Plus) only. For the project I am using withStyles.

import { withStyles } from "@material-ui/core";

I tried using:

"@media (width: 414px) and (height: 628px)": {}

I tried "@media (device-width: 414px) and (device-height: 628px)": {}
Tried both examples and is not working. Does someone have any ideas how to do it? Thank you


Get this bounty!!!

#StackBounty: #reactjs #typescript HTMLElement definition in typescript.lib/lib.dom.d.ts was overridden by @types/react/global.d.ts

Bounty: 150

enter image description here

The compiler find the definition of HTMLElement, but the definition from react/global.d.ts is taken instead of typescript/lib/lib.dom.d.ts.

Here’s the compiler error:

Property 'value' does not exist on type 'EventTarget'.  TS2339

Here are the differences:

In react/global.d.ts

interface Element { }

interface HTMLElement extends Element { }

In typescript/lib/lib.dom.d.ts

interface HTMLElement extends Element, GlobalEventHandlers, DocumentAndElementEventHandlers, ElementContentEditable, HTMLOrSVGElement, ElementCSSInlineStyle {
    accessKey: string;
    readonly accessKeyLabel: string;
    autocapitalize: string;
    dir: string;
    draggable: boolean;
    hidden: boolean;
    innerText: string;
    lang: string;
    readonly offsetHeight: number;
    readonly offsetLeft: number;
    readonly offsetParent: Element | null;
    readonly offsetTop: number;
    readonly offsetWidth: number;
    spellcheck: boolean;
    title: string;
    translate: boolean;
    click(): void;
    addEventListener<K extends keyof HTMLElementEventMap>(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;
    addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;
    removeEventListener<K extends keyof HTMLElementEventMap>(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;
    removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;
}

So my question is: how to make the compiler choose typescript/lib/lib.dom.d.ts before the one from React? Any help would be greatly appreciated!

Edit: here’s the tsconfig.json, correctly referencing the TS lib:

{
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "incremental": true, // Enable incremental compilation by reading/writing information from prior compilations to a file on disk
    "sourceMap": true, // Generate corrresponding .map file
    "declaration": true, // Generate corresponding .d.ts file
    "noUnusedLocals": true, // Report errors on unused locals
    "noUnusedParameters": true, // Report errors on unused parameters
    "jsx": "react"
  },
  "include": [
    "src"
  ]
}


Get this bounty!!!

#StackBounty: #reactjs #google-maps #google-map-react google-map-react draggable marker – onChildMouseMove not working on mobile

Bounty: 300

This works beautifully on a computer, but I just tried testing it on mobile, and none of the onChildMouse event handlers are recognized. I’ve tried finding other event handlers, but onChildMouseXXX is the only ones I see for this package. How can I make the draggable marker work? Is there another event I can use, or a known work around to this issue?

import React from "react"
import PropTypes from "prop-types"

import GoogleMapReact from 'google-map-react';

const Marker = () => <div className="markerCircle"></div>;

class DraggableMap extends React.Component {
  constructor(props) {
    super(props);


    this.state = {
      center: {
        lat: 0,
        lng: 0
      },
      zoom: 11,
      lat: 0,
      lng: 0,
      draggable: true,
      loaded: false
    }

    this.onChildMouseMove = this.onChildMouseMove.bind(this)
    this.onChildMouseUp = this.onChildMouseUp.bind(this)
    this.onChildMouseDown = this.onChildMouseDown.bind(this)
  }

  componentDidMount() {
    this.setState({
      center: {
        lat: this.props.lat,
        lng: this.props.lng,
      },
      lat: this.props.lat,
      lng: this.props.lng,
      loaded: true
    })
  }

  componentDidUpdate() {
    if(this.props.lat != this.state.lat) {
      this.setState({
        center: {
          lat: this.props.lat,
          lng: this.props.lng,
        },
        lat: this.props.lat,
        lng: this.props.lng,
        loaded: true
      })
    }
  }

  onChildMouseDown(){
      console.log('mouse down')
      // set map no draggable
        this.setState({
            draggable: false,
        });
    }

    onChildMouseUp(){
      console.log('mouse up')
      //set map draggable again
        this.setState({
            draggable: true,
        });
    }

    onChildMouseMove(hoverKey, childProps, mouse){
      console.log('move mouse')
      // Change item data with new coordinates
      // you need set here own store and update function
      this.setState({
        lat: mouse.lat,
        lng: mouse.lng
      }, () => this.props.updateLatLng(this.state.lat, this.state.lng))
    }


  render() {
    if(!this.state.loaded) {
      return null
    }
    return (
      // Important! Always set the container height explicitly
      <div style={{ height: '100%', width: '100%' }}>
        <GoogleMapReact
          bootstrapURLKeys={{ key: 'yesItIsMyRealKeyHere' }}
          defaultCenter={this.state.center}
          center={{lat: this.state.lat, lng: this.state.lng}}
          defaultZoom={this.state.zoom}
          draggable={this.state.draggable}
          onChildMouseDown={() => this.onChildMouseDown()}
          onChildMouseUp={() => this.onChildMouseUp()}
          onChildMouseMove={(key, childProps, mouse) => this.onChildMouseMove(key, childProps, mouse)}
        >
          <Marker
              key={'id'}
              item={'n'}
              lat={this.state.lat}
              lng={this.state.lng}
            />
        </GoogleMapReact>
      </div>
    );
  }

}

export default DraggableMap;


Get this bounty!!!

#StackBounty: #javascript #reactjs #gatsby #use-effect #prismic.io Page Templates re-rendering on every click in Prismic & Gatsby

Bounty: 50

I’ve been trying to diagnose why I’ve got useEffect running multiple times when I click a <Link> component, even with empty dependencies. I found a good way to figure out where my problem lies, using the solution in this answer.

Essentially I’m adding a useEffect that console logs components went they re-render, and I went all the way up the tree till I found the highest level component that doesn’t re-render.

useEffect(()=>{
  console.log('this component is rendered');
},[]);

I’m using gatsby-plugin-layout, and my AppLayout component is the component where the re-render does not occur, meaning that the problem lies within my page templates, as defined in gatsby-source-prismic-graphql, which are the next things down the tree where the console logs the page change when the <Link> is clicked. All this to say, I’m not entirely sure where the problem here lies, or if there is something within my AppLayout or gatsby-config.js that is throwing it off and making this behavior occur. How can I fix it so my pages aren’t constantly re-rendering? Included below are my AppLayout and gatsby-config.js.

Thanks in advance.

gatsby-config.js

/* eslint-disable @typescript-eslint/camelcase */
const path = require('path');

require('dotenv').config({
  path: `.env.${process.env.NODE_ENV}`,
});

const site = require('./config/site');

const pathPrefix = site.pathPrefix === '/' ? '' : site.pathPrefix;

module.exports = {
  pathPrefix: site.pathPrefix,
  siteMetadata: {
    siteUrl: site.url + pathPrefix,
    pathPrefix,
    title: site.title,
    titleAlt: site.titleAlt,
    titleTemplate: site.titleTemplate,
    description: site.description,
    banner: site.logo,
    headline: site.headline,
    siteLanguage: site.siteLanguage,
    ogLanguage: site.ogLanguage,
    author: site.author,
    twitter: site.twitter,
    facebook: site.facebook,
  },
  plugins: [
    'gatsby-plugin-react-helmet-async',
    'gatsby-plugin-typescript',
    'gatsby-plugin-sharp',
    'gatsby-plugin-sitemap',
    'gatsby-transformer-sharp',
    {
      resolve: 'gatsby-source-filesystem',
      options: {
        name: 'images',
        path: path.join(__dirname, `src`, `assets`, `images`),
      },
    },
    {
      resolve: 'gatsby-plugin-manifest',
      options: {
        name: 'one-day-doors-and-closets',
        short_name: 'starter',
        start_url: '/',
        background_color: '#663399',
        theme_color: '#663399',
        display: 'minimal-ui',
        icon: 'src/assets/images/icon.png',
      },
    },
    {
      resolve: '@sentry/gatsby',
      options: {
        dsn: process.env.SENTRY_DSN,
        enabled: (() => ['production'].indexOf(process.env.NODE_ENV) !== -1)(),
      },
    },
    {
      resolve: 'gatsby-plugin-react-svg',
      options: {
        rule: {
          include: path.resolve(__dirname, 'src/assets/svg'),
        },
      },
    },
    {
      resolve: 'gatsby-source-prismic-graphql',
      options: {
        repositoryName: `${process.env.PRISMIC_REPOSITORY_NAME}`,
        defaultLang: 'en-us',
        path: '/preview',
        previews: false,
        accessToken: `${process.env.PRISMIC_ACCESS_TOKEN}`,
        pages: [
          {
            type: 'Homepage',
            match: '/',
            component: require.resolve('./src/pages/index.tsx'),
          },
          {
            type: 'Landing',
            match: '/:uid',
            component: require.resolve('./src/templates/landing.tsx'),
          },
          {
            type: 'Legal',
            match: '/:uid',
            component: require.resolve('./src/templates/legal.tsx'),
          },
          {
            type: 'Locator',
            match: '/:uid',
            component: require.resolve('./src/pages/locations.tsx'),
          },
          {
            type: 'Product',
            match: '/products/:uid',
            component: require.resolve('./src/templates/product.tsx'),
          },
        ],
      },
    },
    {
      resolve: 'gatsby-plugin-layout',
      options: {
        component: require.resolve('./src/components/app-layout/AppLayout.tsx'),
      },
    },
  ],
};

AppLayout.tsx

import React, { ReactNode, useEffect, useState } from 'react';

import { Devtools } from 'components/devtools/Devtools';
import { Footer } from 'components/footer/Footer';
import { Header } from 'components/header/Header';
import { NavigationSkipLink } from 'components/navigation-skip-link/NavigationSkipLink';
import { AppContext } from 'contexts/app-context/AppContext';
import { graphql, StaticQuery } from 'gatsby';
import { usePrevious } from 'hooks/use-previous';
import { TransitionGroup, CSSTransition } from 'react-transition-group';

import s from './AppLayout.scss';

interface AppLayoutProps {
  props: any;
  children: ReactNode;
  location: any;
}

const isDev = process.env.NODE_ENV === 'development';

export const MainContentId = 'maincontent';
export const timeout = 250;

const NavQuery = graphql`
  query NavQuery {
    prismic {
      allNavigations {
        edges {
          node {
            ...NotificationBar
            ...NavigationItems
            ...FooterNavigationItems
            ...LegalNavigationItems
          }
        }
      }
    }
  }
`;

// eslint-disable-next-line react/display-name
export default ({ children, location: { pathname } }: AppLayoutProps) => {
  const [fadeEffectVisible, setFadeEffectVisible] = useState(false);
  const [page, setPage] = useState(pathname);
  const prevPage = usePrevious(pathname);

  useEffect(
    () => () => {
      if (pathname !== prevPage) {
        setFadeEffectVisible(true);
        setPage(page);
      }
    },
    [pathname],
  );

  const handleFadeEffectEntered = () => {
    setTimeout(() => {
      setFadeEffectVisible(false);
    }, 50);
  };

  return (
    <StaticQuery
      query={`${NavQuery}`}
      render={(data) => (
        <>
          <AppContext>
            <CSSTransition
              in={fadeEffectVisible}
              timeout={timeout}
              classNames={{
                enter: s.fadeEffectEnter,
                enterActive: s.fadeEffectEnterActive,
                enterDone: s.fadeEffectEnterDone,
                exit: s.fadeEffectExit,
                exitActive: s.fadeEffectExitActive,
              }}
              onEntered={handleFadeEffectEntered}
            >
              <div className={s.fadeEffect} aria-hidden="true" />
            </CSSTransition>

            <NavigationSkipLink />
            <Header navigationContent={data.prismic.allNavigations.edges[0].node} />
            <TransitionGroup component={null}>
              <CSSTransition
                key={pathname}
                timeout={timeout}
                classNames={{
                  enter: s.pageEnter,
                }}
              >
                <div id={MainContentId} className={s.layout}>
                  {children}

                  <Footer navigationItems={data.prismic.allNavigations.edges[0].node} />

                  {isDev && <Devtools />}
                </div>
              </CSSTransition>
            </TransitionGroup>
          </AppContext>
        </>
      )}
    />
  );
};


Get this bounty!!!

#StackBounty: #reactjs #autocomplete #material-ui #autofill Chrome, Edge – Disable autofill / autocomplete for fields

Bounty: 200

I have a ReactJS app that is built with Material UI.

The target browsers are Chrome and Microsoft Edge, both latest version and two latest versions (so in total 3 versions).

What I want to achieve:

Disable the autocomplete and autofill for textinput fields.

I have searched for a long time but could not find a working solution.

What I have tried so far:

  1. autoComplete={"off"}
  2. autoComplete={"false"}
  3. autoComplete={"xyz"} so Autocomplete with a custom value
  4. autoComplete="new-password"> but it does not work in Edge
  5. Implementation of a solution, that adds HTML readonly attribute to each input field at the beginning, removes it on focus and adds it again onBlur of the texfield. This does not work and moreover leads to a defect that moving to another text input by using tabulator on the keyboard is not possible any more.

It is no solution for me, to wrap every field in a <form> element.

Happy to see an approach to solve this.


Get this bounty!!!

#StackBounty: #reactjs #optimization #rendering Reducing React table rerendering

Bounty: 500

I have a table with two columns, each of which are editable. The table also includes the ability to add new entries. The problem I’m running into is that whenever a single row is edited, each row is re-rendered. For larger tables this causes noticeable keystroke delays when editing a single row. Any ideas as to how this can be prevented?

I haven’t been able to replicate the performance problems in a "small" example, but https://codesandbox.io/s/zen-williams-r8pii?file=/src/App.js is the basic functionality. I’ve tried dropping React.memo in a few places to no avail (I’m a newbie at this stuff)

Thanks for any help!


Get this bounty!!!

#StackBounty: #javascript #reactjs #gmail #signature is there any way to copy the rendered HTML of a div?

Bounty: 100

I am working on a signature generator for emails and I want to copy the final signature with the press of a button instead of manually selecting the signature and copying it to the clipboard. This means I need the image, text and styling for them.

I have tried a couple of variants, including the w3schools one, but no success, some of them are only copying the text, but without the styling.

Example: https://www.mail-signatures.com/signature-generator/


Get this bounty!!!

#StackBounty: #javascript #reactjs #redux #antd How to change Antd form initialValues depends at url or id?

Bounty: 50

I got same component with Antd form for add/edit article. With pathes in router

<Route path="/add" component={ !currentUser ? Login : ArticleEditor } />
<Route path="/article/:id/edit" component={ !currentUser ? Login : ArticleEditor } />

When I click "edit" button I add initialValues to form, than if I click "Create new article" url changes to "/add", but form didn’t update values. Values remains from edited article. How to update form values? Tried to set initialValues depends at path, or "id" but its not worked. How to update antd form values in that case?

const initialValues = this.props.location.pathname === '/add' ? {} : {
      title: this.props?.title,
      body: this.props?.body,
      description: this.props?.description
    };

Here you can see the component code – codesandbox link


Get this bounty!!!

#StackBounty: #reactjs #authentication #firebase-authentication #one-time-binding I wonder if this really is the correct way to use onA…

Bounty: 50

Following this react-firestore-tutorial
and the GitHub code. I wonder if the following is correct way to use the onAuthStateChanged or if I have understod this incorrect I’m just confused if this is the right way.

CodeSandBox fully connect with a test-account with apikey to Firebase!! so you can try it what I mean and I can learn this.

(NOTE: Firebase is blocking Codesandbox url even it’s in Authorised domains, sorry about that but you can still see the code)

t {code: "auth/too-many-requests", message: "We have blocked all
requests from this device due to unusual activity. Try again later.",
a: null}a:

Note this is a Reactjs-Vanilla fully fledge advanced website using only;
React 16.6
React Router 5
Firebase 7

Here in the code the Firebase.js have this onAuthStateChanged and its called from two different components and also multiple times and what I understand one should only set it up once and then listen for it’s callback. Calling it multiple times will that not create many listeners?

Can someone have a look at this code is this normal in Reactjs to handle onAuthStateChanged?
(srccomponentsFirebasefirebase.js)

import app from 'firebase/app';
import 'firebase/auth';
import 'firebase/firestore';

class Firebase {
  constructor() {
    app.initializeApp(config);

   .......
  }

  .....

  onAuthUserListener = (next, fallback) =>
    this.auth.onAuthStateChanged(authUser => {
      if (authUser) {
        this.user(authUser.uid)
          .get()
          .then(snapshot => {
            const dbUser = snapshot.data();

            // default empty roles
            if (!dbUser.roles) {
              dbUser.roles = {};
            }

            // merge auth and db user
            authUser = {
              uid: authUser.uid,
              email: authUser.email,
              emailVerified: authUser.emailVerified,
              providerData: authUser.providerData,
              ...dbUser,
            };

            next(authUser);
          });
      } else {
        fallback();
      }
    });

  user = uid => this.db.doc(`users/${uid}`);

}

export default Firebase;

This two rect-higher-order Components:

First withAuthentication:
(srccomponentsSessionwithAuthentication.js)

import React from 'react';

import AuthUserContext from './context';
import { withFirebase } from '../Firebase';

const withAuthentication = Component => {
  class WithAuthentication extends React.Component {
    constructor(props) {
      super(props);

      this.state = {
        authUser: JSON.parse(localStorage.getItem('authUser')),
      };
    }

    componentDidMount() {
      this.listener = this.props.firebase.onAuthUserListener(
        authUser => {
          localStorage.setItem('authUser', JSON.stringify(authUser));
          this.setState({ authUser });
        },
        () => {
          localStorage.removeItem('authUser');
          this.setState({ authUser: null });
        },
      );
    }

    componentWillUnmount() {
      this.listener();
    }

    render() {
      return (
        <AuthUserContext.Provider value={this.state.authUser}>
          <Component {...this.props} />
        </AuthUserContext.Provider>
      );
    }
  }

  return withFirebase(WithAuthentication);
};

export default withAuthentication;

And withAuthentication:
(srccomponentsSessionwithAuthorization.js)

import React from 'react';
    import { withRouter } from 'react-router-dom';
    import { compose } from 'recompose';
    
    import AuthUserContext from './context';
    import { withFirebase } from '../Firebase';
    import * as ROUTES from '../../constants/routes';
    
    const withAuthorization = condition => Component => {
      class WithAuthorization extends React.Component {
        componentDidMount() {
          this.listener = this.props.firebase.onAuthUserListener(
            authUser => {
              if (!condition(authUser)) {
                this.props.history.push(ROUTES.SIGN_IN);
              }
            },
            () => this.props.history.push(ROUTES.SIGN_IN),
          );
        }
    
        componentWillUnmount() {
          this.listener();
        }
    
        render() {
          return (
            <AuthUserContext.Consumer>
              {authUser =>
                condition(authUser) ? <Component {...this.props} /> : null
              }
            </AuthUserContext.Consumer>
          );
        }
      }
    
      return compose(
        withRouter,
        withFirebase,
      )(WithAuthorization);
    };
    
    export default withAuthorization;


Get this bounty!!!