Changing the Color of the Drawer in Material-UI React

Hi I wanted to change the Background Color of my MUI Drawer. I have been looking for Days but found nothing. Here is my Header Code:

import { AppBar, Toolbar, Typography, makeStyles, Button, IconButton, Drawer, Link, MenuItem } from "@material-ui/core";
import React, { useEffect, useState } from "react";
import { Link as RouterLink } from "react-router-dom";
import MenuIcon from "@material-ui/icons/Menu";
import logo from "./Icon.png";

const useStyles = makeStyles (() => ({
    header: {
        backgroundColor: "#1b1b1b",
        paddingRight: "0px",
        paddingLeft: "18px",
        "@media (max-width: 900px)": {
            paddingLeft: 0,
        },
    },
    menuButton: {
        fontFamily: "Inter, sans-serif",
        fontWeight: 700,
        size: "18px",
        marginLeft: "38px",
    },
    toolbar: {
        display: "flex",
        justifyContent: "space-between",
    },
    drawerContainer: {
        padding: "20px 30px",
        color: "inherit",
    },
}));

const headersData = [
    {
        label: "Featured",
        href: "/featured",
    },
    {
        label: "Favorites",
        href: "/favorites",
    },
    {
        label: "My Account",
        href: "/account",
    },
    {
        label: "Discord",
        href: "/discord",
    }
];

export default function Header() {
    const [state, setState] = useState({
        mobileView: false,
        drawerOpen: false
    });

    const { mobileView, drawerOpen } = state;

    useEffect(() => {
        const setResponsivness = () => {
            return window.innerWidth < 900
            ? setState((prevState) => ({ ...prevState, mobileView: true }))
            : setState((prevState) => ({ ...prevState, mobileView: false, drawerOpen: false }));
        };

        setResponsivness();
        window.addEventListener("resize", () => setResponsivness());

        return () => {
            window.removeEventListener("resize", () => setResponsivness());
        }
    }, []);

    const { header, menuButton, toolbar, drawerContainer } = useStyles();
    const displayDesktop = () => {
        return (
            <Toolbar className={toolbar}>
                <a href="/">{smomodsLogo}</a>
                <div>{getMenuButtons()}</div>
            </Toolbar>
        )
    };

    const getDrawerChoices = () => {
        return headersData.map(({ label, href }) => {
            return (
                <Link
                    {...{
                        component: RouterLink,
                        to: href,
                        color: "inherit",
                        style: { textDecoration: "none" },
                        key: label,
                    }}
                >
                    <MenuItem>{label}</MenuItem>
                </Link>
            )
        })
    }

    const displayMobile = () => {
        const handleDrawerOpen = () =>
            setState((prevState) => ({ ...prevState, drawerOpen: true }));
        const handleDrawerClose = () =>
            setState((prevState) => ({ ...prevState, drawerOpen: false }));
        return (
            <Toolbar>
                <IconButton
                    {...{
                        edge: "start",
                        color: "inherit",
                        "aria-label": "menu",
                        "aria-haspopup": "true",
                        onClick: handleDrawerOpen,
                    }}
                >
                    <MenuIcon/>
                </IconButton>
                <Drawer
                    {...{
                        anchor: "left",
                        open: drawerOpen,
                        onClose: handleDrawerClose,
                    }}
                >
                    <div className={drawerContainer}>{getDrawerChoices()}</div>
                </Drawer>
                <div><a href="/">{smomodsLogo}</a></div>
            </Toolbar>
        )
    }

    const smomodsLogo = (
        <Typography variant="h6" component="h1">
            <img src={logo} alt="SMOMods" width={224} height={70}/>
        </Typography>
    )

    const getMenuButtons = () => {
        return headersData.map(({ label, href }) => {
            return (
                <Button
                    {...{
                        key: label,
                        color: "inherit",
                        to: href,
                        component: RouterLink,
                        className: menuButton
                    }}
                >
                    {label}
                </Button>
            );
        });
    };

    return (
        <header>
            <AppBar className={header}>{mobileView ? displayMobile() : displayDesktop()}</AppBar>
        </header>
    );
}

The Drawer uses Material-UI in ReactJS. I would like to have an answer asap. I am really new to React and it’s my first time using it. I have added something like BackgroundColor: “#1b1b1b” to the code before but it only changed the Background Color behind the buttons and not the full Drawer!

Google sheets Script – Sort sheet by column AP under category headers (colored background)

I am fairly new to Javascript/Apps Script.

I have a sheet that contains a few categories and their data on a single sheet. I am trying to create a script that sorts whats under each category (header) by column AP.

Currently we are manually selecting the range then running the following macro to sort by the column.

function SortAP() {
  var spreadsheet = SpreadsheetApp.getActive();
  spreadsheet.getActiveRange()
  .sort({column: 42, ascending: true});
};

I want to have this query a row for a header and then run the function. Is this possible?

Here is an example sheet of what our headers look like

Searching for category with subcategories in javascript array of objects

I’m building a search functionality where I need to search for a specific value to be find by part of its text.
So I’ve got an example object:

const data = [
  {
    org_name: "A PFS COUNTRY TESTS",
    clients: [
      {
        name: "Abu Dhabi",
        type: "Yacht",
        currency: "EUR",
        notifications: {
          for_action: 0,
          for_attention: 0
        },
        unpaid_invoices: {
          total: 0,
          ok_to_pay: 0,
          reviewed: 0
        }
      },
      {
        name: "Australia",
        type: "Yacht",
        currency: "AUD",
        notifications: {
          for_action: 0,
          for_attention: 0
        },
        unpaid_invoices: {
          total: 0,
          ok_to_pay: 0,
          reviewed: 0
        }
      },
      {
        name: "Bermuda",
        type: "Yacht",
        currency: "EUR",
        notifications: {
          for_action: 0,
          for_attention: 0
        },
        unpaid_invoices: {
          total: 0,
          ok_to_pay: 0,
          reviewed: 0
        }
      }
    ]
  },
  {
    org_name: "Music Tours",
    clients: [
      {
        name: "Music Demo",
        type: "Office",
        currency: "GBP",
        notifications: {
          for_action: 0,
          for_attention: 0
        },
        unpaid_invoices: {
          total: 0,
          ok_to_pay: 0,
          reviewed: 0
        }
      },
      {
        name: "Summer Tour",
        type: "Office",
        currency: "GBP",
        notifications: {
          for_action: 0,
          for_attention: 0
        },
        unpaid_invoices: {
          total: 0,
          ok_to_pay: 0,
          reviewed: 0
        }
      },
      {
        name: "Winter Tour",
        type: "Yacht",
        currency: "USD",
        notifications: {
          for_action: 0,
          for_attention: 0
        },
        unpaid_invoices: {
          total: 0,
          ok_to_pay: 0,
          reviewed: 0
        }
      }
    ]
  },
  {
    org_name: "Dariusz Sandbox 1",
    clients: [
      {
        name: "Dariusz Test Client 1",
        type: "Yacht",
        currency: "EUR",
        notifications: {
          for_action: 0,
          for_attention: 0
        },
        unpaid_invoices: {
          total: 0,
          ok_to_pay: 0,
          reviewed: 0
        }
      },
      {
        name: "Dariusz Test Client 2",
        type: "House",
        currency: "GBP",
        notifications: {
          for_action: 0,
          for_attention: 0
        },
        unpaid_invoices: {
          total: 0,
          ok_to_pay: 0,
          reviewed: 0
        }
      },
      {
        name: "Dariusz Test Client 3",
        type: "Aircraft",
        currency: "USD",
        notifications: {
          for_action: 0,
          for_attention: 0
        },
        unpaid_invoices: {
          total: 0,
          ok_to_pay: 0,
          reviewed: 0
        }
      }
    ]
  },
  {
    org_name: "Dariusz Sandbox 2",
    clients: [
      {
        name: "Dariusz Test Client 1",
        type: "Yacht",
        currency: "EUR",
        notifications: {
          for_action: 0,
          for_attention: 0
        },
        unpaid_invoices: {
          total: 0,
          ok_to_pay: 0,
          reviewed: 0
        }
      }
    ]
  }
];

So if I’m looking for a “Dar” I should receive array with only org_name objects that have clients that include the “Dar” in their name value.

My solution is so far:

const newData = data.map((el) => {
  const filtered = el.clients.filter((client) => {
    if (client.name.includes("Dar")) {
      return client;
    }
  });
  if (filtered.length > 0) {
    return { org_name: el.org_name, clients: filtered };
  }
  
});

console.log("newData is", newData);

But what I’ve got is [undefined, undefined, Object, Object]
instead of [Object, Object]

Match and Print Change Old and New String in Javascript

I want to create a function to compare two strings and return changes in string (like Stack Overflow shows changes in answer which was edited).

Expected results should be.

console.log(detectChange("SHANTI DEVI","SHANT DEVI"));    // SHANT_I_ DEVI
console.log(detectChange("MOHAN SINGH","MOHAN SINGH"));   // MOHAN SINGH
console.log(detectChange("SURESH SINGH","MOHAN SINGH"));  // -MOHAN-_SURESH_ SINGH
console.log(detectChange("SEETA DEVI","SITA SINGH"));     // S-I-_EE_TA -SINGH-_DEVI_
  • First parameter is the new value and second parameter is the old value.
  • Bracket letter or word using “-” if that word or letter was removed
  • The word or letter that was added should be bracketed using “_”

The below code was unsuccessful for me.

function detectChange(name1, name2) {
  name1 = name1.split("");
  name2 = name2.split("");
  var visit = 0;
  var final_name = [];
  if (name2.length > name1.length) {
    nameTmp = name1;
    name1 = name2;
    name2 = nameTmp;
  }

  for (i = 0; i <= name1.length; i++) {
    if (name1[i] == name2[visit]) {
      final_name.push(name1[i]);
      visit++;

    } else if (name1[i] !== null) {
      final_name.push("_" + name1[i] + "_");
      visit++;
    }
  }
  return final_name.join("");
}

// Getting unexpected results
console.log(detectChange("SHANTI DEVI", "SHANT DEVI")); // SHANT_I__ __D__E__V__I_
console.log(detectChange("MOHAN SINGH", "MOHAN SINGH")); // MOHAN SINGH
console.log(detectChange("SURESH SINGH", "MOHAN SINGH")); // _S__U__R__E__S__H__ __S__I__N__G__H_
console.log(detectChange("SEETA DEVI", "SITA SINGH")); // S_E__E__T__A__ __D__E__V__I_

Here every single output is invalid, please help me regarding this how can I handle this.

Split overflowing hours into back dated days based on total hours

I’ve stumbled upon a scenario, where I need to split the JSON object into n number of objects (backdated) if the total hours coming in from the source crosses 24, it should split until the point the total hours have been exhausted.

I have added an input JSON array for clarifying my requirement:

[
    {
        "res": "1001",
        "activity": "First",
        "hours": "20",
        "date": "31/01/2022"
    },
    {
        "res": "1001",
        "activity": "Second",
        "hours": "8",
        "date": "31/01/2022"
    }
]

For res 1001 the total hours gathered from both the activities is 28 hours, which is crossing the threshold of 24 hours for a day, what I would like to achieve is to split any one of the object in such a way that the remaining hours (4 hours → 28-24) gets spread across another object for the previous day.

Here is the desired output:

[
    {
        "res": "1001",
        "activity": "First",
        "hours": "20",
        "date": "31/01/2022"
    },
    {
        "res": "1001",
        "activity": "Second",
        "hours": "4",
        "date": "31/01/2022"
    },
    {
        "res": "1001",
        "activity": "Second",
        "hours": "4",
        "date": "30/01/2022"
    }
]

Had the total hours in input be 60 hours then the output would be required to split across 3 days. 24 + 24 + 12, let’s say activity 1 has 24 hours for date 31/01/2022, activity 2 has 24 hours for 31/01/2022 and activity 3 has 12 hours for date 31/01/2022, then activity 2 would have to shift back to 30/01/2022 and activity 3 would have to shift back to 29/01/2022 as activity 2 has occupied 24 hours on 30/01/2022. Hope this makes sense.

Activities will always have the current day’s date (whenever this calculation will occur).

Any help on this with any one of the scripting langugages preferably JavaScript, would be greatly appreciated, thank you in advance.

How to declare an object with whose name is the value of another object in React? Possibly with JSX?

In my onSubmit function as seen below I’m trying to pass values.pet as an object with number as it’s prop. I then plan on pushing the object into my array of objects that is pet.

 onSubmit={(values, actions) => {
                let freshPet = {
                    {values.pet}: {
                        number: 1
                    }
                }
                   setPets([...pets, freshPet ])
                 }
                }

This is pet’s variable initially created with setPets

{
    cat: {
        number: 1 
    }, 
    dog: {
        number: 1
    }
}

Wrapping values.pet creates a series of errors so I imagine I attempted to utilize jsx wrong. So how would I go about getting a object whose name would be the output of values.pet. The value I’m expecting being a single word string such as “fish” for example.

The link to my entire js file can be found here.

Nested promises with array map

During a POST request I’m trying to insert quiz related data into 2 tables: questions & choices and also to return the saved data. This is how data looks like:

{
    "id": 2,
    "title": "Practice #1",
    "category_id": 2,
    "quizQuestions": [
        {
            "id": 4,
            "time": 180,
            "points": 10,
            "question": {
                "id": 13,
                "choices": [
                    {
                        "id": 55,
                        "is_correct": false
                    },
                    {
                        "id": 57,
                        "is_correct": false
                    },
                    {
                        "id": 56,
                        "is_correct": false
                    },
                ]
            }
        },
        ...
    ]
}

This is the code for parsing the data and executing the inserts:

async processUserQuizQuestions(userQuizId, questionsRaw) {
    const savedQuestions = Promise.all(
        questionsRaw.map(async (question, idx) => {
            const choicesRaw = question.question.choices;
        
            const savedQuestion = await UserQuestion.create({
                uq_id: userQuizId,
                question_id: question.question.id,
                display_order: idx + 1,
            });

            const savedChoices = Promise.all(
                choicesRaw.map(async (choice, idx) => {
                    const savedChoice = await UserChoice.create({
                    uqq_id: userQuestionId,
                    choice_id: choice.id,
                    iteration: Utils.letters()[idx],
                });
                
                return savedChoice;
            );
            
            return { ...savedQuestion, choices: savedChoices };
        }),
    );

    return savedQuestions;
},

The data, both questions and choices, is inserted as expected in the database, but the returning value doesn’t contain the choices:

{[
    {
        "answer_id": 0,
        "id": 83,
        "uq_id": 17,
        "question_id": 13,
        "display_order": 1,
        "updatedAt": "2022-02-02T17:17:25.954Z",
        "createdAt": "2022-02-02T17:17:25.954Z",
        "answer": null,
        "choices": {}
    },
    ...
]}

I assume that there must be something wrong with the nested Promise.all and the array.map because the code doesn’t wait for choices processing.

I don’t think the environment matters but this is an Express server on Node JS with Sequelize and Postgres.

Node copyfile hangs inside docker container

I am working on this node function.

  #copyInCommonFile(tmpDir, commonfile) {
    var newfile = path.join(tmpDir, commonfile.fileName);
    
    try {
      fs.copyFileSync(commonfile.commonFilePath, newfile);
      this.logger.info('Copied file from : ' + commonfile.commonFilePath + ' to ' + newfile);
    } catch (err) {
      throw err
    }
  }

My problem is that no matter what I do, this method hangs with no error. I’ve tried the sync and async methods. This is supposed to copy a file from one directory inside the docker container to another directory. The app just sits there and hangs on the method until it is killed.

The result is that it does create an empty file in the new location.

I have been at this all morning, im out of ideas. do you fine folks have any?

React: Why is my state component not rendering?

I am using context and reducer API for state management and logic.
The below code returns context provider, which is called in App.js.
Why isn’t the component rendering?

SingerState.js

import React, { useReducer } from "react";

import SingerContext from "./singerContext";
import SingerReducer from "./singerReducer";

import { GET_SINGER, SET_LOADING } from "../types";

const SingerState = (props) => {
  console.log('foo')
  const initialState = {
    name: null,
    songs: null,
    loading: false,
  };
  const [state, dispatch] = useReducer(SingerReducer, initialState);

  const getSinger = () => {
    dispatch({
      type: GET_SINGER,
      payload: {
        name: "jb",
        songs: ["song1", "song2"],
      },
    });
  };
  const setLoading = () => {
    dispatch({
      type: SET_LOADING,
    });
  };
  return (
    <SingerContext.Provider
      value={{
        name: state.name,
        songs: state.songs,
        loading: state.loading,
        getSinger,
        setLoading,
      }}
    >
      {props.childer}
    </SingerContext.Provider>
  );
};

export default SingerState;

The entire code is in here: https://codesandbox.io/s/heuristic-shockley-9u2xb?file=/src/App.js:0-411

App.js

import "./App.css";
// import { BrowserRouter as Router, Switch, Route } from "react-router-dom";
import SingerState from "./context/singer/singerState";

import Navbar from "./components/Navbar";
import Singer from "./components/singer/Singer";

export default function App() {
  return (
    <div className='App'>
      <Navbar />
      <SingerState>
        <Singer />
      </SingerState>
    </div>
  );
}

singerReducer.js

import { GET_SINGER, SET_LOADING } from "../types";

const reducer = (state, action) => {
  switch (action.types) {
    case GET_SINGER:
      return {
        ...state,
        name: action.payload.name,
        song: action.payload.song,
        loading: false,
      };
    case SET_LOADING:
      return {
        ...state,
        loading: true,
      };
    default:
      return state;
  }
};
export default reducer;

singerContext.js

import { createContext } from "react";
const singerContext = createContext();
export default singerContext;

ypeError: Cannot read properties of undefined (reading ‘map’)

im done it exactly like in the tutorial and mine is not working, i cant guess why, thanks for any help


import React from "react";
import Day from './Day';

function Month({ month }) {
    return (
        <div className="flex-1 grid grid-cols-7 grid-rows-5">
            {month.map((row, i) => (
                <React.Fragment key={i}>
                    {row.map((day, idx) => (
                        <Day day={day} key={idx} />
                    ))}
                </React.Fragment>
            ))}
        </div>
    )
}

export default Month;

Adding marker on click google maps

I want to be able to add marker on the map by click only after pressing the button “add marker” but the button doesn’t work, the function runs even before I press the button.
https://jsfiddle.net/snoLg0tp/

        <input id="add-markers" type="button" value="Add marker" />
    
        function initMap() {
          const haightAshbury = { lat: 37.769, lng: -122.446 };
        
          map = new google.maps.Map(document.getElementById("map"), {
            zoom: 12,
            center: haightAshbury,
            mapTypeId: "terrain",
          });
          // This event listener will call addMarker() when the map is clicked.
          map.addListener("click", (event) => {
            addMarker(event.latLng);
          });
      document
      .getElementById("add-markers")
        .addEventListener("click", addMarker);
        
            function setMapOnAll(map) {
              for (let i = 0; i < markers.length; i++) {
                markers[i].setMap(map);
              }
            }
            function addMarker(position) {
              const marker = new google.maps.Marker({
                position,
                map,
              });

onClick in button tag is not working in react component

hi i am a newbie in react i am facing a issue in classbased component
given below is my component which i am calling inside another component of react i just want to call the temp function when onClick gets fired but in my case it is not working please let me know where i am doing wrong?

import react from 'react'
import '../../../css/classBased/editor/textFieldForEditor.css'
import addTextField from './leftTrayIconsForEditor'
class TextField extends react.Component {
    
    temp() {
        console.log('hi there')
    }
    render(){
        return (
            <div className='textfield_parent_container'>
          <div>
          <center>
          <div>
          <button onClick={()=> {this.temp()}}>
          <i className="material-icons md-18">article</i>
          </button>
          <button>
          <i className="material-icons md-18">image</i>
          </button>
          <button>
          <i className="material-icons md-18">movie</i>
          </button>
          </div>
          </center>
          </div>
          <textarea className='text' id={`textfield${this.props.widgetNumber}`}></textarea>
          <div className='utilitytrayouter'>
          <center>
          <div className='temp'>
          <button>
          <i className="material-icons md-18">article</i>
          </button>
          <button>
          <i className="material-icons md-18">image</i>
          </button>
          <button>
          <i className="material-icons md-18">movie</i>
          </button>
          </div>
          </center>
          </div>
          </div>
        )
    }
}
export default TextField;

Howto get bootstrap grid row or grid container width in pixels by javascript

Howto get bootstrap grid row or grid container width in pixels by javascript.

I’m using aurelia for javascript but code can be in standard js (please no jquery).

I tried to find this in boostrap website but i’m still confused because there are several dimensions for width: col-xs, colmd… but in fact we are just using 4 dimensions: col-3, col-6, col-9, col-12 and nothing more, so basically i need to get that full width in order to translate pixels to col-x again to match resizing from an html element.

What happens in jest watch mode?

I am currently dealing with very slow jest spec run times (watch mode) in a large-scale application. I would like to debug and figure out what are the slowest parts of the cycle. I’ve been looking around but I couldn’t find a way to debug what’s going on when jest watch mode kicks in.

Suppose I change the file in either spec or source – what are the stages that are executed in jest before the specs are run? I can see jest progress bar but it’s not clear what’s going on before the progress bar starts moving? What happens when it starts moving? I can see that at the end of the progress bar specs are executed because I finally get console.log outputs.

It would be good to have an understanding of the different watch mode stages in order to fix issues with slowness, etc…

Thank you

Dialogflow phone gateway integration issue

I am using Dialogflow es version and want to use Dialogflow phone gateway integration
so a little bit of background, I am now able to integrate it and I got us a phone number and all the basic things are working but if I use custom webhook it is not working currently I am categorizing like this in the webhook node.js function

if (agent.requestSource == 'GOOGLE_TELEPHONY') {
        agent.add('test test');
}else{
        agent.add('not telephony');
}

but it is not working any suggestions?

note If I add something in the dialogflow console itself it is working but not with the custom webhook code.