react.js – React with Typescript – stopwatch component

I’ve been trying to learn React and I’m currently building a time-tracking application. The-end goal of the app will be for users to be able to track time against different tasks from different projects.

This is the stopwatch component I have built, with a start, end and reset button, and I would like to get a code review to see if I’m on the right path in terms of clean code and the use of React hooks.


import * as React from "react";
import styled from "styled-components";
import { useState, useEffect } from "react";

export interface IStopwatchProps {}

export interface IStopwatchState {}

const StartButton = styled.button`
  background: green;
  border-radius: 3px;
  border: 2px solid;
  color: white;
  margin: 0 1em;
  padding: 0.25em 1em;
`;

const StopButton = styled.button`
  background: red;
  border-radius: 3px;
  border: 2px solid;
  color: white;
  margin: 0 1em;
  padding: 0.25em 1em;
`;

const ResetButton = styled.button`
  background: white;
  border-radius: 3px;
  border: 2px solid;
  color: black;
  margin: 0 1em;
  padding: 0.25em 1em;
`;

const Stopwatch: React.FunctionComponent<IStopwatchProps> = (
  props
): React.ReactElement => {
  const (seconds, setSeconds) = useState(0);
  const (minutes, setMinutes) = useState(0);
  const (hours, SetHours) = useState(0);
  const (displaySeconds, setDisplaySeconds) = useState("00");
  const (displayMinutes, setDisplayMinutes) = useState("00");
  const (displayHours, setDisplayHours) = useState("00");
  const (isStopWatchRunning, setStopwatchState) = useState(false);
  const toggleState = () => setStopwatchState(!isStopWatchRunning);
  const resetStopwatch = () => {
    setSeconds(0);
    setMinutes(0);
    SetHours(0);
    setDisplaySeconds("00");
    setDisplayMinutes("00");
    setDisplayHours("00");
    setStopwatchState(false);
  };

  const setDisplayValue = (timeValue: number): string => {
    return timeValue > 9
      ? "" + timeValue.toString()
      : "0" + timeValue.toString();
  };

  useEffect(() => {
    let interval: number = 0;
    if (isStopWatchRunning) {
      interval = window.setInterval(() => {
        let displayValueSeconds = setDisplayValue(seconds);
        setDisplaySeconds(displayValueSeconds);
        let displayValueMinutes = setDisplayValue(minutes);
        setDisplayMinutes(displayValueMinutes);
        let displayValueHours = setDisplayValue(hours);
        setDisplayHours(displayValueHours);
        setSeconds(seconds + 1);
        if (seconds === 59) {
          setSeconds(0);
          setMinutes(minutes + 1);
        }
        if (minutes === 59) {
          setMinutes(0);
          SetHours(hours + 1);
        }
      }, 1000);
    } else if (!isStopWatchRunning && seconds !== 0) {
      clearInterval(interval);
    }
    return () => clearInterval(interval);
  }, (isStopWatchRunning, seconds, minutes, hours));
  return (
    <div>
      <StartButton onClick={toggleState}>Start</StartButton>
      <StopButton onClick={toggleState}>End</StopButton>
      <ResetButton onClick={resetStopwatch}>Reset</ResetButton>
      <h1>
        {displayHours} : {displayMinutes} : {displaySeconds}
      </h1>
    </div>
  );
};

export default Stopwatch;
```

reactjs – Using state in other components in React JS

I have three components.

export default class PermissionHandler extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            permission: true
        }
    }

}

export default class App extends React.Component {
    render() {
        return(
            <PermissionHandler />
            <Component1 />
        )     
    }
}

export default class Component1 extends React.Component {
    render() {
        return(
            <SomeComponent /* visible= true/false depends on permission */ />
        )     
    }
} 

I want PermissionHandler state to be used by any other components directly without using events or local state. Is it possible?

Can I use refs to achieve this goal?

export default class App extends React.Component {
    constructor(props) {
        super(props);
        this.permissionHandler = React.createRef();
    }

    render() {
        return(
            <PermissionHandler ref={this.permissionHandler} />
            <Component1 permissionHandler={this.permissionHandler}/>
            <Component2 permissionHandler={this.permissionHandler} />
        )     
    }
}

export default class Component1 extends React.Component {
    render() {
        return(
            <SomeComponent visible={this.props.permissionHandler.currenct.state.permission} />
        )     
    }
} 

But Component1 doesnt rerender when the state of PermissionHandler updates

reactjs – ¿Acceder a un array dentro de un objeto y extraer una propiedad?

Se que es una pregunta bastante básica, pero mi nivel es este. La cuestión es que sé que es algo no muy difícil pero no caigo, y por más que busco no encuentro lo que yo exáctamente quiero hacer.

introducir la descripción de la imagen aquí

Aquí el arbol de propiedades del objeto de la API de pokemon. Quiero hacerme una pokédex e ir sacando propiedades para añadirlas a una ficha de pokemon. Ya he podido acceder como pueden ver a name y a id, y ahora quiero acceder a abilities. Creo recordar que era usando .map(), pero no se bien como hacerlo. El tema es que quiero acceder a abilities > 0 > ability > name, para que diréctamente por la pantalla se muestre el “static”.

Es usando Array.map()? Hay alguna otra forma más ordenada y correcta? Gracias de antemano.

html – interact with SVG Marker element with event handlers in React(JS)

see demo: https://codesandbox.io/s/svg-marker-element-ekkkx?file=/src/App.js
as you can see – the events on the marker element just do not fire.

what can do to make it work, or any idea for an easy alternative implementing arrowhead without the use of SVG marker elements, or any sort of workaround?

(you can see a more detailed explanation of the problem here )

How can I display the list of profiles with ReactJS and Redux,

I want some help for this issue in which I want to display the profiles from the Database when I click “Developers”, I typed correctly with the course of this MERN Project but I get these errors?!

Any help please, I’m quite beginner with ReactJS and Redux.. I would be very thankful..

This is the link for the github project: https://github.com/GnichiMohamed/DEVCONNECTOR

javascript – Reactjs, control list of list of input

import React from "react";
import "./styles.css";

const testData = (
  {
    name: "list 1",
    content: (
      {
        id: 1,
        value: " this is value 1 of list 1"
      },
      {
        id: 2,
        value: " this is value 2 of list 1"
      },
      {
        id: 3,
        value: " this is value 3 of list 1 "
      }
    )
  },
  {
    name: "list 2",
    content: (
      {
        id: 1,
        value: " this is value 1 of list 2"
      },
      {
        id: 2,
        value: " this is value 2 of list 2"
      },
      {
        id: 3,
        value: " this is vainput'liste 3 of list 2"
      }
    )
  }
);


class MyList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: this.props.list
    };
  }
  handleChange = (e, index) => {
    const newData = this.state.data;
    newData(index) = e.target.value;
    this.setState({
      data: newData
    });
  };

  updateData = newData => {
    this.setState({
      data: newData
    });
  };

  add = () => {
    const newData = this.state.data;
    newData.push({
      id: newData.length + 1,
      value: "new data"
    });
    this.setState({
      data: newData
    });
  };

  remove = (e, index) => {
    const newData = this.state.data;
    newData.splice(index, 1);
    this.setState({
      data: newData
    });
  };

  save = (e, index) => {
    //TODO
  };

  render() {
    return (
      <div className="App">
        <button onClick={this.add}> Add </button>
        <button onClick={this.save}> save </button>
        <tr>input'list
          {this.state.data.map((item, index) => (
            <td>
              <input
                value={item.value}
                onChange={e => this.handleChange(e, index)}
              />
              title
              <button onClick={e => this.remove(e, index)}> remove </button>
            </td>
          ))}
        </tr>
      </div>
    );
  }
}

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      title: testData(0).name,
      data: testData(0).content
    };
    this.ref = React.createRef();
  }

  changeList = (e, index) => {
    this.setState({
      title: testData(index).name,
      data: testData(index).content
    });
    this.ref.current.updateData(testData(index).content);
  };

  render() {
    return (
      <>
        {testData.map((item, index) => (
          <button onClick={e => this.changeList(e, index)}>
            {" "}
            {item.name}{" "}
          </button>
        ))}
        this is {this.state.title}
        <MyList ref={this.ref} list={this.state.data}>
          {" "}
        </MyList>{" "}
      </>
    );
  }
}
export default App;

I need some basic method like show list, save, add more input in list, remove … And with my code, everything works fine. But I feel it’s not clean since there’s many ways to do 1 thing in React. Can someone read it and give me some feedback? There’s 2 things I thought are not good, but I don’t know how to improve:

function handleChange of component MyList: I have to calculator index of input to re-render.

I use A Ref to update and get Data from component MyList.

react.js – React App with Redux

Decided to give ReactJS + Redux + Typescript a try this weekend.
Going to include the code first and then summerize a few questions that came into my mind during development.
Also posting here to get general feedback on what I can improve on.

The whole project on codesandbox.io

index.tsx

import * as React from "react";
import * as ReactDOM from "react-dom";
import App, { PipelineItemType } from "./App";
import { createStore } from "redux";
import { Provider } from "react-redux";
import { EXECUTE } from "./Execute";
import { COPY } from "./Copy";

export const ADD_PIPELINE_ITEM = "ADD_ITEM";
interface AddPipelineItemAction {
  type: typeof ADD_PIPELINE_ITEM;
  data: PipelineItemType;
}

export const UPDATE_PIPELINE_ITEM = "UPDATE_ITEM";
interface UpdatePipelineItemAction {
  type: typeof UPDATE_PIPELINE_ITEM;
  data: PipelineItemType;
}

export const DELETE_PIPELINE_ITEM = "DELETE_ITEM";
interface DeletePipelineItemAction {
  type: typeof DELETE_PIPELINE_ITEM;
  idx: number;
}

export type ActionTypes =
  | AddPipelineItemAction
  | UpdatePipelineItemAction
  | DeletePipelineItemAction;

export interface StoreState {
  pipelineItems: PipelineItemType();
}

const initialState: StoreState = {
  pipelineItems: (
    { type: EXECUTE, idx: 0, commandLine: "npm run build" },
    { type: EXECUTE, idx: 1, commandLine: "npm run test" },
    { type: COPY, idx: 2, source: "sourceDir", destination: "destinationDir" },
    { type: EXECUTE, idx: 3, commandLine: "npm run deploy" }
  )
};

let nextComponentId = 0;
function pipelineActions(
  state = initialState,
  action: ActionTypes
): StoreState {
  switch (action.type) {
    case ADD_PIPELINE_ITEM:
      return {
        ...state,
        pipelineItems: (
          ...state.pipelineItems,
          { ...action.data, idx: nextComponentId++ }
        )
      };
    case UPDATE_PIPELINE_ITEM:
      return {
        ...state,
        pipelineItems: state.pipelineItems.map((el: PipelineItemType) => {
          return el.idx === action.data.idx ? action.data : el;
        })
      };
    case DELETE_PIPELINE_ITEM:
      console.log("Delete" + action.idx);
      return {
        ...state,
        pipelineItems: state.pipelineItems.filter(
          (el: PipelineItemType) => el.idx !== action.idx
        )
      };
    default:
      return state;
  }
}

let store = createStore(pipelineActions);

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById("app")
);

App.tsx

import React, { Dispatch, Component } from "react";
import {
  StoreState,
  ADD_PIPELINE_ITEM,
  ActionTypes,
  UPDATE_PIPELINE_ITEM,
  DELETE_PIPELINE_ITEM
} from ".";
import { connect } from "react-redux";
import { ExecuteComponent, Execute, EXECUTE } from "./Execute";
import { CopyComponent, Copy, COPY } from "./Copy";

export type PipelineItemType = Copy | Execute;

export interface AppProps {
  pipelineItems: PipelineItemType();
  addItem: (data: PipelineItemType) => void;
  updateItem: (data: PipelineItemType) => void;
  removeItem: (idx: number) => void;
}

export class App extends Component<AppProps> {
  render() {
    return (
      <div className="App">
        {this.props.pipelineItems.map(el => {
          switch (el.type) {
            case COPY:
              return (
                <CopyComponent
                  removeItem={this.props.removeItem}
                  updateItem={this.props.updateItem}
                  key={el.idx}
                  idx={el.idx}
                  source={el.source}
                  destination={el.destination}
                />
              );
            case EXECUTE:
              return (
                <ExecuteComponent
                  removeItem={this.props.removeItem}
                  updateItem={this.props.updateItem}
                  key={el.idx}
                  idx={el.idx}
                  commandLine={el.commandLine}
                />
              );
            default:
              return <div>???</div>;
          }
        })}
        <br />
        <br />
        Debug Output:
        <br />
        {JSON.stringify(this.props.pipelineItems)}
      </div>
    );
  }
}

const mapStateToProps = (state: StoreState) => ({
  pipelineItems: state.pipelineItems
});

const mapDispatchToProps = (dispatch: Dispatch<ActionTypes>) => ({
  addItem: (data: PipelineItemType) =>
    dispatch({ type: ADD_PIPELINE_ITEM, data: data }),
  updateItem: (data: PipelineItemType) =>
    dispatch({ type: UPDATE_PIPELINE_ITEM, data: data }),
  removeItem: (idx: number) =>
    dispatch({ type: DELETE_PIPELINE_ITEM, idx: idx })
});

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(App);

Copy.tsx

import React, { Component } from "react";
import { PipelineItemType } from "./App";

export const COPY = 'COPY'
export interface Copy {
  type: typeof COPY;
  idx: number;
  source: string;
  destination: string;
}

export interface CopyItemProps {
  idx: number;
  source: string;
  destination: string;
  updateItem: (data: PipelineItemType) => void;
  removeItem: (idx: number) => void;
}

export class CopyComponent extends Component<CopyItemProps> {
  render() {
    return (<div>Will copy from
      <input type="text" defaultValue={this.props.source} onBlur={(e) => this.props.updateItem({ type: COPY, idx: this.props.idx, source: e.target.value, destination: this.props.destination })} />
      to<input type="text" defaultValue={this.props.destination} onBlur={(e) => this.props.updateItem({ type: COPY, idx: this.props.idx, source: this.props.source, destination: e.target.value })} />
      <input type="button" value="X" onClick={(e) => this.props.removeItem(this.props.idx)} />
    </div>)
  };
}

Execute.tsx

import React, { Component } from "react";
import { PipelineItemType } from "./App";

export const EXECUTE = "EXECUTE";
export interface Execute {
  type: typeof EXECUTE;
  idx: number;
  commandLine: string;
}

export interface ExecuteItemProps {
  idx: number;
  commandLine: string;
  updateItem: (data: PipelineItemType) => void;
  removeItem: (idx: number) => void;
}

export class ExecuteComponent extends Component<ExecuteItemProps> {
  render() {
    return (
      <div>
        Will execute
        <input
          type="text"
          defaultValue={this.props.commandLine}
          onBlur={e =>
            this.props.updateItem({
              type: EXECUTE,
              idx: this.props.idx,
              commandLine: e.target.value
            })
          }
        />
        <input
          type="button"
          value="X"
          onClick={e => this.props.removeItem(this.props.idx)}
        />
      </div>
    );
  }
}

Questions:

  • Is there a better way to render a list of different react components? Currently using a switch as type-guard to get the current component to render. Coming from a C++ background this feels kinda wrong since you do something different based on the type.
    I was thinking about storing the react component instance inside the array but I read somewhere that this is bad and will most likely cause multiple issues (Unfortunately I can’t find the source anymore)

  • Should I keep the add/update/removeItem handler together?
    Technically I could dispatch updateItem and removeItem from the child-components, but for me it seems cleaner to keep them bundled together with the addItem method, which means I have to define a callback for the child components.

  • In the App.tsx is there an easier way for keys?
    Currently using a counter to have unique keys for the Component List

  • When creating a new child component via addItem I need to set idx to an arbitrary value, since it is part of the interface. Is there a better way to do this? Just creating a new interface that doesn’t include idx seems a bit redundant for me.

react.js – Page for editing an item from an expenses list

I have been working on a beginner project, learning React and Typescript. The project is an expense manager application and I have tried splitting most of my applications into simple short components.
For the EditExpensePage component I have connected it to the Redux store for the app, in order to be able to access the state and to dispatch actions.

I would like to get some feedback on the code I’ve written, and ways I could improve it.

The Expense interface :

export interface Expense {
    id: string;
    description: string;
    note?: string;
    amount: number;
    createdAt: number;
}

The EditExpensePage :

import * as React from "react";
import { RouteComponentProps } from "react-router";
import * as Redux from 'redux';
import {withRouter} from 'react-router';
import {connect} from 'react-redux';
import { Expense } from "../types/Expense";
import { AppState } from "../Store/configureStore";
import { compose } from "redux";
import ExpenseForm from "./ExpenseForm";
import { AppActions } from "../types/Actions";
import { addExpense, removeExpense } from "../Actions/expenses";

type PathParamsType = {
  id: string;
};
//component own props
type PropsType = RouteComponentProps<PathParamsType> & {
  id: string;
};

interface StateProps {
    expenses: Expense()
}

interface DispatchProps{
    addExpense : (expense : Expense) => any,
    removeExpense : (expenseId : string) => any
}

type Props = PathParamsType & PropsType & StateProps & DispatchProps;

function GetSelectedExpense(id : string, expenses : Expense()){
    for (var i=0 ; i<expenses.length; i++){
        if (expenses(i).id === id)
        {
            return expenses(i);
        }
    }
}

const EditExpensePage: React.FunctionComponent<Props> = (props): any => {
    let selectedExpense = GetSelectedExpense(props.match.params.id, props.expenses)
    return (
    <ExpenseForm description={selectedExpense?.description} amount={selectedExpense?.amount} onSubmit={(expense) => {

        for (let i = 0; i< props.expenses.length ; i++){
            if (props.expenses(i) === selectedExpense)
            {
                props.removeExpense(selectedExpense.id);
                props.addExpense(expense);
            }
        }

    }}/>
 )
};

const mapStateToProps = (state : AppState) :StateProps => {
    return({
        expenses : state.expenses
    })
}

const mapDispatchToProps = (dispatch : Redux.Dispatch<AppActions>) : DispatchProps => {
    return {
        addExpense : (expense : Expense) => dispatch(addExpense(expense)),
        removeExpense : (id : string) => dispatch(removeExpense(id))
    }
}

export default compose(
    withRouter,
    connect(mapStateToProps, mapDispatchToProps))(EditExpensePage);
```

reactjs – Declare a variable in a conditional structure in React

I am with an application ReactJS + TypeScript I've watched that cannot declare a variable within a conditional block, although it is done yes or yes (within the block if Or from else, must always be declared in advance, that prevents me, for example In certain cases, use a constant. I think I remember it's the same when you don't use it typescript.

Invalid example:

if (false) {
    const x = 1;
} else {
    const x = 2;
}

// Uso la variable x

Valid example:

let x;
if (false) {
    x = 1;
} else {
    x = 2;
}

// Uso la variable x

Note: I know the examples are very simple and you can declare the constant by assigning the value with a ternary, but this is not the intention, this code is meant to illustrate the question.

What is the cause of this?

python – Reactjs Proxy to Flask does not work for polls, but for forms

Hello folks, I have a reaction frontend that I created with create-react-app getcode-client and a backend that a flask App.

in my package.json I have defined the proxy as follows: "proxy":"http://localhost:5000/"

I tried to use all of these proxy values:
http://localhost:5000/
http://127.0.0.1:5000
http://127.0.0.1:5000/
http://localhost:5000

None of these proxy setups work.

My reaction app is used to create it create-react-app
My frontend is in a separate folder next to the backend directory

Even if a or

is called, then it is forwarded to the backend, but the problem is with fetch or axios Calls