code reuse – How to compose a potentially in-place editable page with React?

I have a public website with profile pages of people for the general public to see and a separate admin website with user login where people can edit their own profile page.

The profile page is editable on the admin website but should not be editable on the public website and want the admin website to have pretty much the same layout for the profile page but in editing mode.

Editing should happen in place in a WYSIWYG style, and the profile page has a fixed layout of its contents, including a profile picture, a person’s name, some contact info, a teaser text and a longer text section.

Text sections use Markdown with WYSIWYG editing.

The public website should not need to serve code for editing functionality, and I want to keep both websites consistent in terms of layout with minimal effort required to change the layout.

How can I ensure consistency of layouts with minimal effort while avoiding having to serve unnecessary code for editing functions on the public website?

My current approach would be to provide a skeleton component that accepts specific children satisfying particular interfaces and rendering them in the right places.

So I would fill that skeleton with editable components on the admin website and read-only components on the public website, but this still means a lot of duplication regarding the components used to fill into the skeleton.

javascript – Button conditionals in React

I wrote some conditionals for a button component and everything works, but I feel like this is not the right way of writing conditionals. Would appreciate it if anyone could review my code.


import buttonStyles from './Button.module.scss';
import { Link } from "gatsby";

interface Props {
  content: string,
  color: string,
  path?: string,
  type: string
}

export default function Button(props: Props): JSX.Element {
  const availableColors = ('blue', 'grey', 'dark-grey', 'white');
  const borderColors = ('');

  if(!availableColors.includes(props.color)) {
    console.error(`"${props.color} color key not available for button style`);
    return;
  }

  if(!props.content) {
    console.error(`"${props.content} is not valid as content`);
    return;
  }

  let buttonStyle = buttonStyles(`button--${props.color}`);
  let elementType;

  if(props.type == 'link' || props.type == 'button') {
    if(props.type == 'link') {
      elementType = <Link to={ props.path } className={ buttonStyle }>{ props.content }</Link>
    } else {
      elementType = <button className={ buttonStyle }>{ props.content }</button>
    }
  } else {
    console.error(`"${props.type} is not valid as a type. Use 'link' or 'button'`);
    return;
  }

  return (
    <React.Fragment>
      { elementType }
    </React.Fragment>
  );
}
```

react native – Managing redux state of mutiple switch components

I have a react native native app and I am fetching the state of the toggle buttons from an API and then putting them into redux state. I do not like the way I have implemented it cause it seems very messy and was wondering if anyone would have any suggestions on how to refactor the code.

Below is screen that calls my redux state for each toggle switch.

const SiteSettingsDashboard = (props) => {
  const dispatch = useDispatch();

  const alarmNotificationsToggle = useSelector(
    (state) => state.registration.alarmNotifications
  );
  const armingNotificationToggle = useSelector(
    (state) => state.registration.armingNotifications
  );

  const faultsNotificationToggle = useSelector(
    (state) => state.registration.faultsNotifications
  );

  const engineerNotificationToggle = useSelector(
    (state) => state.registration.engineerNotifications
  );

  const techZoneNotificationToggle = useSelector(
    (state) => state.registration.techZoneNotifications
  );

  const eventTimerNotificationToggle = useSelector(
    (state) => state.registration.eventTimerNotifications
  );

  const noCommsNotificationToggle = useSelector(
    (state) => state.registration.noCommsNotifications
  );

  const ToggleSwitchInput = (value) => {
    dispatch(registrationActions.toggleNotificationInput(value));
  };

  return (
    <View>
        <View style={{ flexDirection: "row" }}>
          <Text>{IMLocalized("Arming")}</Text>
          <Switch
            style={styles.right}
            trackColor={{ false: "#FF0000", true: "#008000" }}
            thumbColor={armingNotificationToggle ? "#008000" : "#FF0000"}
            ios_backgroundColor="#3e3e3e"
            onValueChange={() => ToggleSwitchInput("arming")}
            value={armingNotificationToggle}
          />
        </View>
        <Card.Divider />
        <View style={{ flexDirection: "row" }}>
          <Text>{IMLocalized("Faults")}</Text>
          <Switch
            style={styles.right}
            trackColor={{ false: "#FF0000", true: "#008000" }}
            thumbColor={faultsNotificationToggle ? "#008000" : "#FF0000"}
            ios_backgroundColor="#3e3e3e"
            onValueChange={() => ToggleSwitchInput("faults")}
            value={faultsNotificationToggle}
          />
        </View>
        <Card.Divider />
        <View style={{ flexDirection: "row" }}>
          <Text>{IMLocalized("Engineer")}</Text>
          <Switch
            style={styles.right}
            trackColor={{ false: "#FF0000", true: "#008000" }}
            thumbColor={engineerNotificationToggle ? "#008000" : "#FF0000"}
            ios_backgroundColor="#3e3e3e"
            onValueChange={() => ToggleSwitchInput("engineer")}
            value={engineerNotificationToggle}
          />
        </View>
        <Card.Divider />
        <View style={{ flexDirection: "row" }}>
          <Text>{IMLocalized("TechZone")}</Text>
          <Switch
            style={styles.right}
            trackColor={{ false: "#FF0000", true: "#008000" }}
            thumbColor={techZoneNotificationToggle ? "#008000" : "#FF0000"}
            ios_backgroundColor="#3e3e3e"
            onValueChange={() => ToggleSwitchInput("techZone")}
            value={techZoneNotificationToggle}
          />
        </View>
        <Card.Divider />
        <View style={{ flexDirection: "row" }}>
          <Text>{IMLocalized("EventTimers")}</Text>
          <Switch
            style={styles.right}
            trackColor={{ false: "#FF0000", true: "#008000" }}
            thumbColor={eventTimerNotificationToggle ? "#008000" : "#FF0000"}
            ios_backgroundColor="#3e3e3e"
            onValueChange={() => ToggleSwitchInput("eventTimer")}
            value={eventTimerNotificationToggle}
          />
        </View>
        <Card.Divider />
        <View style={{ flexDirection: "row" }}>
          <Text>{IMLocalized("NoComms")}</Text>
          <Switch
            style={styles.right}
            trackColor={{ false: "#FF0000", true: "#008000" }}
            thumbColor={noCommsNotificationToggle ? "#008000" : "#FF0000"}
            ios_backgroundColor="#3e3e3e"
            onValueChange={() => ToggleSwitchInput("noComms")}
            value={noCommsNotificationToggle}
          />
        </View>
        <Card.Divider />
      </Card>
    </View>
  );
};

const styles = StyleSheet.create({
  errorText: {
    color: "red",
  },
  right: {
    flex: 1,
  },
});

export default SiteSettingsDashboard; 

I have the state of each of the buttons declared in redux and this does not change.

export const types = Object.freeze({
  ToggleAlarmNotification: "TOGGLE_ALARM_NOTIFICATION",
  ToggleArmingNotification: "TOGGLE_ARMING_NOTIFICATION",
  ToggleFaultsNotification: "TOGGLE_FAULTS_NOTIFICATION",
  ToggleEngineerNotification: "TOGGLE_Engineer_NOTIFICATION",
  ToggleTechZoneNotification: "TOGGLE_TECH_ZONE_NOTIFICATION",
  ToggleEventTimerNotification: "TOGGLE_EVENT_TIMER_NOTIFICATION",
  ToggleNoCommsNotification: "TOGGLE_NO_COMMS_NOTIFICATION",
});


const initialState = {
  isRequestingLogoImage: false,
  alarmNotifications: false,
  armingNotifications: false,
  faultsNotifications: false,
  engineerNotifications: false,
  techZoneNotifications: false,
  eventTimerNotifications: false,
  noCommsNotifications: false,
};

And here is my reducer file. I do this for all of the toggle buttons.

case types.ToggleNoCommsNotification:
      return {
        ...state,
        noCommsNotifications: !state.noCommsNotifications,
      };

Como fazer um CheckBox dinâmico com React Hook?

Galera, como posso fazer esse checkbox dinâmico? Porque desta forma que está ai tenho que criar um useState para cada checkbox, mas quando eu for puxar esses valores do banco irão vir diâmicamente, como criar os useState também dinamicamente? Snack do código funcionando: https://snack.expo.io/@wendellchristian/checkbox

import React, { useEffect, useState } from 'react';
import { Text, View, StyleSheet } from 'react-native';
import Constants from 'expo-constants';
import { RadioGroup, CheckBox  } from 'react-native-btr';

export default function App() {
    const (checked, setChecked) = useState(false);
    const (checked2, setChecked2) = useState(false);
    const (checked3, setChecked3) = useState(false);

  return (
    <View style={styles.container}>

      <View style={styles.viewCheckbox}>
        <View style={styles.checkbox}>
          <CheckBox
            checked={checked}
            onPress={item => setChecked(!checked)}
            color='#009688'
          />
        </View>
        <Text onPress={item => setChecked(!checked)}> Checkbox 1</Text>
      </View>

      <View style={styles.viewCheckbox}>
        <View style={styles.checkbox}>
          <CheckBox
            checked={checked2}
            onPress={item => setChecked2(!checked2)}
            color='#009688'
          />
        </View>
        <Text onPress={item => setChecked2(!checked2)}> Checkbox 2</Text>
      </View>
      
      <View style={styles.viewCheckbox}>
        <View style={styles.checkbox}>
          <CheckBox
            checked={checked3}
            onPress={item => setChecked3(!checked3)}
            color='#009688'
          />
        </View>
        <Text onPress={item => setChecked3(!checked3)}> Checkbox 3</Text>
      </View>

    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
    padding: 8,
  },
  paragraph: {
    margin: 24,
    fontSize: 18,
    fontWeight: 'bold',
    textAlign: 'center',
  },
  viewCheckbox: {
    flexDirection: "row",
    marginBottom: 10,
  },
  checkbox: {
    width: 24,
  }
});

babeljs – How to use React Cosmos in a TypeScript mono-repo

I’m having trouble getting React Cosmos to work in a TypeScript monorepo.

Though light, their instructions work fine for TypeScript in a single package, but as soon as I try to use code from another TypeScript package in the monorepo it complains that it doesn’t understand the type syntax (clearly it’s not transpiling the shared files).

To demonstrate the problem simply, I have a minimal TypeScript monorepo (here) with two packages:

  • packages/client (@mono/client)
  • packages/shared (@mono/shared)

The client renders a single page with a simple <Greeting firstName="Joe" /> component in it. The greeting component uses a getGreeting function from the shared package and renders its output to screen. I use parcel to serve the page and it compiles it fine. However if I try to use React Cosmos I get this error:

(Cosmos) Using default cosmos config
(Cosmos) See you at http://localhost:5000
(Cosmos) Using default webpack config
(Cosmos) Building webpack...
webpack built f4d924ce19e1768283e9 in 1628ms
✖ 「wdm」: assets by status 2.6 MiB (cached) 1 asset
runtime modules 24.8 KiB 13 modules
modules by path ../../node_modules/ 2.3 MiB 243 modules
modules by path ./src/components/greeting/*.tsx 424 bytes
  ./src/components/greeting/index.fixture.tsx 182 bytes (built) (code generated)
  ./src/components/greeting/index.tsx 242 bytes (built) (code generated)
../shared/src/greeter.ts 39 bytes (built) (code generated) (1 error)
ws (ignored) 15 bytes (optional) (built) (code generated)

ERROR in ../shared/src/greeter.ts
Module build failed (from ../../node_modules/babel-loader/lib/index.js):
SyntaxError: /ts-monorepo-playground/packages/shared/src/greeter.ts: Unexpected token, expected "," (1:32)

> 1 | export function getGreeting(name: string) {
    |                                 ^
  2 |   return `Hello ${name}`;
  3 | }
  4 |

Some more info

  • Cosmos version: 5.5.0
  • Cosmos config: None
  • Webpack version: 5.1.3
  • Webpack config: None
  • Babel config:

packages/client/.babelrc

{
  "presets": (
    "@babel/preset-react",
    (
      "@babel/preset-typescript",
      {
        "isTSX": true,
        "allExtensions": true
      }
    )
  ),
  "plugins": (
    (
      "module-resolver",
      {
        "root": ("./"),
        "alias": {
          "@mono/shared": "../shared/src"
        }
      }
    )
  )
}

I do not wish to do any pre-compilation of shared packages before running cosmos, cosmos should be able to use babel to compile everything it needs on the fly, so hot reloading can work.

It’s like React Cosmos/Babel is not respecting my babel config for files in other packages.

react – Como Somar os Valores De Dentro De Um Array?

Preciso somar os valores do atributo “valores” que estão dentro de objetos separados dentro de um Array.

Tentei fazer um FOR para somar todos os “item.valor”, mas o valor de “resultado” é 0.

Podem me ajudar?

API: https://gitlab.com/desafio-conta-simples/developer/-/blob/master/mocks/transacoes.json

Código:

class ResumoValores extends Component   {

constructor(props){
    super(props);

    this.state = {
        //Array que recebe os Itens da API
        transacoes: (),
    }   
}

componentDidMount(){
    fetch("http://localhost:3000/transacoes")
    .then(resultado => resultado.json().then(dados => this.setState({transacoes: dados})))
    
}

render() {
    return (
     
    <Container>

        {
        //NavBar
        }
        <NavBar></NavBar>    
        {

        //CheckBox
        
        }
           
        {
        //Tabela com os dados
        }
        <Table striped bordered hover variant="dark">
            <thead>
                <tr>
                <th>Resultado</th>
                </tr>
            </thead>
            <tbody>

               { 
                //Chama o Array Transacoes e Faz um Map para listar os itens
                this.state.transacoes.map((item, indice)  => {
                    var resultado = 0;
                    var somaValores = item.valor
                    for ( var i = 0; i < somaValores.length; i++ ){
                    resultado += somaValores(i);
                    }
                    console.log(resultado);
                        return (

                            <tr key={indice}>
                            <td> {resultado}</td>
                            </tr>
                           )
                     })
                }


            </tbody>
        </Table>
    </Container>
    )
}

}

export default ResumoValores;

react – SPFX Webpart requires page to be edited to load data

I have created an SPFX webpart with react which displays images from SharePoint library. The Library path is configurable through Webpart Property pane. Whenever I edit the Page and webpart properties, It loads webpart and displays images But if i save and refresh the page, it does not display the images(blank webpart). Same behavior even if page is Published.

Everytime I need to edit the page to load the webpart. Is there any setting that is missed ? I have also added PreConfigured entries in webpart manifest.json file.

javascript – React Private Routes implementation with adal

I have integrate aad authentication using react-adal client and secure paths using private routes method

I’m not satisfied with the code structure so I would like to improve it.

Here’s the code

index.js

import { runWithAdal } from 'react-adal';
import { authContext } from './auth.js';

const DO_NOT_LOGIN = true;

runWithAdal(authContext, () => {
  console.log("authcontext", authContext)
  // eslint-disable-next-line
  require('./indexApp.js');

}, DO_NOT_LOGIN);

indexApp.js

import React from 'react';
...
import ReactDOM from 'react-dom';
import App from './App';
import {
    BrowserRouter as Router,
    Route,
} from "react-router-dom";
import Welcome from './components/WelcomeComponent/WelcomeComponent'
import PrivateRoute from './components/PrivateRouteComponent/PrivateRouteComponent'

ReactDOM.render(
    <Router>
        <React.StrictMode>
            <ProviderNorth theme={teamsTheme}>
                <Provider store={store}>
                    <PrivateRoute exact path="/" component={App}></PrivateRoute>
                    <Route exact path="/welcome" component={Welcome}>
                    </Route>
                </Provider>
            </ProviderNorth>
        </React.StrictMode>
    </Router>,
    document.getElementById('root')
);
serviceWorker.unregister();

First as I’m making logging via a button is there a way to get rid of indexApp ? I tried to eliminate it but when I login, the welcomepath does not redirect to / anymore and stays in /welcome.

Welcome.js

Here I check if user is loggedin first then redirect to / or not

...
import { authContext } from '../../auth'

import {
    Redirect,
} from "react-router-dom";
import React from 'react';


function Welcome(props) {
    const isLogged = authContext.getCachedUser();
    return (
        isLogged === null ? (
            <div>
                <Header as="h1" content="Welcome to Heedify Reports Page" />
                <Header as="h2" content="Login" />
                <Flex gap="gap.smaller">
                    <Button content="Login" primary onClick={() => {
                        authContext.login().then(data => {
                            console.log("log in", data)
                        })
                    }} />
                </Flex>
            </div>) : <Redirect
                to={{
                    pathname: "/"
                }}
            />
    )
}

export default Welcome

PrivateRoute

import React from ‘react’;
import {
Redirect,
Route,
} from “react-router-dom”;
import { authContext } from ‘../../auth’;

const PrivateRoute = ({ component: Component, ...rest }) => {
    return (
        <Route
            {...rest}
            render={props => {
                return authContext.getCachedUser() !== null ? (
                    <Component {...props} />
                ) : (
                        <Redirect
                            to={{
                                pathname: "/welcome"
                            }}
                        />
                    )
            }}></Route>)
}

export default PrivateRoute

react – Redux props undefined depois de re-rendeização

Estou tentando fazer com que cada componente puxe as informações da API apenas quando aparecer na viewport, usando react intersection observer.

Tenho um hook que cria a ref para o componente e adiciona a função de callback que puxa as informações da API

import { useEffect, useCallback } from "react";
import { useInView } from "react-intersection-observer";

export const useLazyLoader = (
  onEnterView: (component?: string) => any,
  component: string
) => {
  const (ref, inView) = useInView({
    triggerOnce: true,
    rootMargin: "-100px",
  });
  const innerEnterView = useCallback(() => {
    onEnterView(component);
  }, (onEnterView, component));

  useEffect(() => {
    inView && innerEnterView();
  }, (inView, innerEnterView));
  return ref;
};

Na page, eu crio um ref para cada elemento e faço uma verificação pra ver qual está na tela no momento pra chamar a função correspondente aos seus dados

  const onEnterView = useCallback(
    (component) => {
      const componentDispatches: { (key: string): any } = {
        stock: () => dispatch(getStock()),
        product: () => dispatch(getSellers()),
        orders: () => dispatch(getOrders({ cnpj: "123456789" })),
      };
      return componentDispatches(
        component as keyof typeof componentDispatches
      )();
    },
    (dispatch)
  );
  const stockRef = useLazyLoader(onEnterView, "stock");
  const productRef = useLazyLoader(onEnterView, "product");
  const ordersRef = useLazyLoader(onEnterView, "orders");

Os componentes visuais ficam assim:

   <ProductPanel
    ref={productRef}
    isLoading={!seller}
    data={seller && seller.marketplace}
    tagData={MarketplaceTagObj}
   />

    <StockSituation
      ref={stockRef}
      isLoading={!stockSituation}
      stockSituation={stockSituation}
    />

    <TableOrders ref={ordersRef} isLoading={!orders} orders={orders} />

O problema aqui é que cada vez que um elemento entra na viewport, a page re-renderiza diversas vezes, além disso, quando eu recarrego a página com o scroll em algum componente que não seja o primeiro e vou subindo o scroll, a função onEnterView é chamada, causando re-renderização e os dados que já estavam no redux ficam undefined. Existe alguma forma de evitar essa re-renderização?

Eu criei um sandbox pra ilustrar o que acontece, que pode ser acessado aqui

No sandbox eu não consegui reproduzir o problema de perder dados do redux porque quando eu recarrego a página, o scroll volta pro topo, mas o problema de re-renderização ainda acontece.

react – Possíveis problemas com um chat usando socket.io

Olá, tudo bem?

Eu tenho mais uma dúvida do que um problema, tenho uma aplicação de chat que fiz usando Socket.IO, ReactJS e MongoDB, acontece que, vendo alguns tutoriais a galera trazia as informações diretamente do MongoDB toda vez que uma nova mensagem era enviada ao servidor. Isso me preocupou, pois o pouco conhecimento que tenho sobre banco de dados, me diz que ficar enviando requisições ao banco, inserindo e buscando valores, pode ser problemático, gostaria de entender se minha linha de raciocínio está correta, ou há algo na tecnologia do MongoDB que permite que isso seja possível e viável.

Abaixo segue o trecho de código que se refere a enviar a mensagem e adiciona-la ao banco, as mensagens mostradas para o usuário são trazidas pelo socket.io, não as trago direto do banco pela preocupação que descrevi, ao invés disso apresento todas as mensagens que estão salvas no banco quando o usuário acessa o chat pela primeira vez.

Código no servidor

Agradeço desde já!