Accessing a nested JSON object to read into a table in React

I have a JSON object which I’m trying to parse into a table using React, however I’m having trouble using .map() to try to create a row for every unique combination of course code, name, transferable_credits, transferable_credits -> institution, transferable_credits -> name, and url. I can’t seem to figure out how to get the key-values of the nested arrays within each JSON root key-value pair.

My React component so far:

import data from './data.json'

const Home = () => {

    return ( 
        <div className="home">
            <table>
                <thead>
                    <tr>
                        <th>Course Code</th>
                        <th>Vendor Institution</th>
                        <th>Vendor Course</th>
                    </tr>
                </thead>
            <tbody>
                {Object.keys(data).map(function(key, index) {
                    return (
                        <tr key={index}>
                            <td>{key}</td>
                            {Object.keys(data[key].transferable_credits).forEach(function(key2) {
                                return (
                                    <td>{key2.institution}</td>
                                )
                            })}
                        </tr>
                    )})

                }
            </tbody>
            </table>
        </div>

     );
}
 
export default Home;

VueJS – How to use flatpickr to only choose month and day, but not year

I want to create a flat picker in my Vue project, so that the users only input their birth month and birth day, but not birth year. Reason behind this is a lot of the customers refuse to provide their full birth date, but is more willing to provide only the month and day.

I know how to create a date picker on my Vue project, as such:

*CustomerModal.vue*
<template>
  ...
  
          <flat-picker
            :config="dpconfig"
            class="form-control datepicker"
            v-model="end_date"
            :placeholder="$t('End Date')"
            ref="End Date"
            name="end_date"
          >
          </flat-picker>

...
</template>

import flatPicker from "vue-flatpickr-component";

export default {
  components: {
    flatPicker,
  },
  data: {
    dpconfig: {
      wrap: true,
      altInput: true,
      dateFormat: "Y-m-d",
      altFormat: "Y-m-d",
      ariaDateFormat: "Y-m-d",
    },
  },

The above code will create a date picker. It has year, month and day. However, what can I do if I want to only ask the users for month and day?

Thank You!

Uncaught SyntaxError: Cannot use import statement outside a module when import custom lib in google chrome extension

I am create a javascript lib and tried to import into my project, I tried to added dependencies into the google chrome extension code like this in the package.json:

"js-wheel": "git+https://github.com/jiangxiaoqiang/js-wheel.git",

and import modual in the google chrome extension project like this:

import { Auth,Validate } from "js-wheel";

when I run this code, the console shows error like this:

Uncaught SyntaxError: Cannot use import statement outside a module

this is the js-wheel package.json:

{
  "name": "js-wheel",
  "version": "1.0.0",
  "description": "",
  "type": "module",
  "main": "index.js",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/jiangxiaoqiang/js-wheel.git"
  },
  "author": "[email protected]",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/jiangxiaoqiang/js-wheel/issues"
  },
  "homepage": "https://github.com/jiangxiaoqiang/js-wheel#readme"
}

I have already tried to define the js-wheel to module, why still shows this error? where am I doing wrong? what should I do to fix this problem? In the public lib, I define the index.js like this:

import BaseMethods from "./src/utils/data/checker";
import Validate from "./src/utils/data/validate";
import Auth from "./src/auth/extension/auth";

export default {
    BaseMethods,
    Validate,
    Auth
}

and define the export function like this way:

const Validate = {
    
    mobileCheck: (mobile) => {
        let reg = /^[1][3,4,5,7,8][0-9]{9}$/
        return reg.test(mobile)
    }
}

export default Validate

How can I solve this error? “export ‘default’ (imported as ‘App’) was not found in ‘./App’ (possible exports: App)” (im using react)

heyyy. i wanted to try out react with this tutorial.

at the moment I have only made the data structure. unfortunately i always get an error when compiling.


Error

Compile failed.

Attempted import error: './App' does not contain default export (imported as 'App').
Assets by state 1.6 MiB [cached] 2 assets
Assets by path . 930 bytes
  asset index.html 658 bytes [emitted]
  asset-manifest.json 272 bytes [emitted]
cached modules 1.39 MiB (javascript) 1 bytes (asset) 28.1 KiB (runtime) [cached] 144 modules
./src/index.js 1.34 KiB [built]

ERROR in ./src/index.js 8:38-41
export 'default' (imported as 'App') was not found in './App' (possible exports: App)

webpack 5.66.0 compiles with 1 error in 63 ms

App.js

import React from 'react'

import { Footer, Blog, Possibility, Features, WhatWELOVEU, Header } from './containers';
import { CTA, Brand, Navbar } from './components';

export const App = () => {
    return (
        <div className='App'>
            <div className='gradient_bg'>
                <Navbar />
                <Header />
            </div>
            <Brand />
            <WhatWELOVEU />
            <Features />
            <Possibility />
            <CTA />
            <Blog />
            <Footer />

            
        </div>
    )
}

index.js

import React from 'react';
import ReactDOM from 'react-dom';

import App from './App';

ReactDOM.render(<App />, document.getElementById('root'));

these two files are in the “src” folder. in the “src” folder there are also the components and containers. everything is described in the tutorial and the data structure is the same.
enter image description here


In the folder components and container are .jsx and css files. all css FIles nid empty, in the jsx files you can find the same code always adapted to the name of the file.

p.ex.
Article.jsx

import React from 'react'
import './article.css';

const Article = () => {
    return (
        <div>
            Article
        </div>
    )
}

export default Article

enter image description here


In containers and components are also index files.

components/index.js

export { default as Article } from './article/Article';
export { default as Brand } from './brand/Brand';
export { default as CTA } from './cta/CTA';
export { default as Feature } from './feature/Feature';
export { default as Navbar } from './navbar/Navbar';

containers/index.js

export { default as Blog } from './blog/Blog';
export { default as Features } from './features/Features';
export { default as Footer } from './footer/Footer';
export { default as Header } from './header/Header';
export { default as Possibility } from './possibility/Possibility';
export { default as WhatWELOVEU } from './whatWELOVEU/whatWELOVEU';

D3.js style and class override not work as my expectation

May I know why my class “bold-header” styles didn’t override to the first row<tr> of the table?

HTML:

<style>
    .bold-header{
        background-color:navy;
        color:white;
    }
</style>

<table border="1">
    <tr>
        <td>ID</td>
        <td>Name</td>
    </tr>
    <tr>
        <td>001</td>
        <td>John</td>
    </tr>
    <tr>
        <td>002</td>
        <td>Alex</td>
    </tr>
    <tr>         
        <td>003</td>
        <td>Maxwell</td>
    </tr>
</table>

Script:

d3.select("table").selectAll("td").style("background-color", "lightblue").style("width", "100px");

d3.select("table").select("tr").classed("bold-header", true);

I expect this result:
my expectation

but it gave me this:
actual result

FabricJS – How to make selected object in canvas unselectable?

I want one of the objects that have loaded on canvas to be forever selected even if I click on another object.
That one object is still selected as in the below picture.

Is it possible to do so?

I have tried with the code below but it still couldn’t help, it just made the object not selectable.
When I clicked on elsewhere besides the object, it just deselected the object.

object.selectable = false;

I

How to create a new page and route programatically in React.js with React Router

I’m building a blog website with React.js with React-router. I have a “blog.js” file that renders all titles of the blogs the page looks like this:

Blog.js

    function Blog() {
    
    
      return (
        <div>
          <Header />
          <div className="blog-page-title">
          <h1>Blog</h1>
          </div>
          <div className="blog">
            <Articles title="Title" text="lorem ipsum dolor amet" />
            <Articles title="Title" text="lorem ipsum dolor amet" />
            <Articles title="Title" text="lorem ipsum dolor amet" />
            <Articles title="Title" text="lorem ipsum dolor amet" />
            <Articles title="Title" text="lorem ipsum dolor amet" />
            <Articles title="Title" text="lorem ipsum dolor amet" />
            <Articles title="Title" text="lorem ipsum dolor amet" />
            <Articles title="Title" text="lorem ipsum dolor amet" />
      
          </div>
          <Footer />
        </div>
      );
    }

export default Blog;

enter image description here

When I click on the title, it should route to the corresponding article. But do I have to create a new Route and a new js file manually for each article to achieve this? For instance, can I do something like whenever there is a new Articles component in blog.js it will go and create a new route and a js file automatically?

Decode Base64 with UCS-2 Encoding

I want to decode the Base64 result of MS-SQL Server in javascript, but I can’t find a true solution. I know SQL Server uses UCS-2 encoding, and I have to use the same encoding to decode in javascript.

For example, for MwZEBicGRQY= the encoded result must be سلام.

Do you have any solution to decode that using javascript?

Build a class that have 3 instances variables : itemname, quantity and price

1.Build a class that have 3 instances variables : itemname, quantity and price. Build a method that can input number of item bought by a customer in XYZ supermarket. (add suitable exception handling type to make sure user input the correct number); itemname, quantity and price will be insert based on number of item bought. (use looping statement) and calculate total price to be paid. Build another method to calculate the total price

querySelectorAll for multiple objects

I have this code, i need to change JS code for use it on all navigation class names. The purpose is to create a drop down menu but the javascript code takes only the first of the elements with class name navigation.

On inquiring I found out we need to use a querySellectorAll but I can’t get it to work.

I give you below the code that works for only one object hoping someone will be able to show me how to use it for all objects with class name navigation. Thanks for your help.

let navigation = document.querySelector('.navigation');

navigation.onclick = function() {
  navigation.classList.toggle('active')
}
.active {
  color: blue;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">

<div class="navigation">
  <ul>
    <span><i class="fa-regular fa-pen-to-square"></i></span>
    <span><i class="fa-regular fa-heart"></i></span>
    <span><i class="fa-regular fa-trash-can"></i></span>

    <div id="marker"></div>
  </ul>
</div>
<div class="navigation">
  <ul>
    <span><i class="fa-regular fa-pen-to-square"></i></span>
    <span><i class="fa-regular fa-heart"></i></span>
    <span><i class="fa-regular fa-trash-can"></i></span>

    <div id="marker"></div>
  </ul>
</div>
<div class="navigation">
  <ul>
    <span><i class="fa-regular fa-pen-to-square"></i></span>
    <span><i class="fa-regular fa-heart"></i></span>
    <span><i class="fa-regular fa-trash-can"></i></span>

    <div id="marker"></div>
  </ul>
</div>

Discord.JS Send all Embeds from Array

multiple embed pushed in array but i need write them in send message without writing specific number Embeds[0], Embeds[1] and more …

i cant find a way.

let Embeds = [];

Embeds.push(new MessageEmbed()
   .setTitle("title")
   .setColor("#3d9e00")
   .setDescription("TEST"));

msg.channel.send({
   embeds: [Embeds[0], Embeds[1]]
});

Integrating DHL Rates API in ReactJs using NodeJs

I want to integrate DHL API into my react js website using node js with express. I have written the backend code and the front end code that would allow me to do this, but when I try to check the rates for a shipment, it gives me this error "Error: Request failed with status code 500"

I don’t know what I am doing wrong when trying to get the DHL API to work.

here is my code:

CheckRates.js:

    const [fromCountires,setFromCountries] = useState("");
    const [fromCountriesCode,setFromCountriesCode] = useState("");
    const [fromCountriesCapital,setFromCountriesCapital] = useState("");
    const [toCountries,setToCountries] = useState("");
    const [toCountriesCode,setToCountriesCode] = useState("");
    const [toCountriesCapital,setToCountriesCapital] = useState("");
    const [weight,setWeight] = useState("");



const getRateEstimate = () => {
                

      const options = {
        method: 'GET',
        url: "http://localhost:3001/api/dhl",
        params: {
          accountNumber: 'myaccountnumber',
          originCountryCode: fromCountriesCode,
          originCityName: fromCountriesCapital,
          destinationCountryCode: toCountriesCode,
          destinationCityName: toCountriesCapital,
          weight: weight,
          length: '5',
          width: '5',
          height: '5',
          plannedShippingDate: date,
          isCustomsDeclarable: 'false',
          unitOfMeasurement: 'metric',
          
        },
        headers: {
          Authorization: 'Basic myauth',  
        }
      };
     
        axios.request(options).then((response) => {
            console.log(response.data);
            setData(response.data);
        }).catch((error) => {
            console.error(error);
        });
      }

nodejs server, index.js:

require('dotenv').config();
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const mysql = require('mysql');
const cookieParser = require('cookie-parser');
const session = require('express-session');
const multer = require('multer');
const path = require('path');
const request = require('request');
const port = 3001
const app = express();

//Middleware 

app.use(cors({
    origin: '*',
    credentials: true,
    methods: ['GET', 'PUT', 'POST'],
    allowedHeaders: ['Content-Type', 'Authorization']
}));
app.use(express.json());
app.use(bodyParser.urlencoded({extended: true}));

app.get("/",(req,res) => {
  res.send("Root App");
})

app.get('/api/dhl', (req, res) => {
  
  request(
    {url: 'https://express.api.dhl.com/mydhlapi/test'},
    (error, response, body) => {
      if (error || response.statusCode !== 200) {
        return res.status(500).json({ type: 'error', });
      }
      res.json(JSON.parse(body));
    }
  )
});

React not redirecting as intended when A function is called in the Routes route

I am building a login and logout system for a react project of mine. I have a navbar setup and I am using react-redirect-dom to create links and redirect links to different pages in order to manage the login system.

In the current project, I have a route that does the processing for the login in the login component. I have another link that processes the signup within the signup component.

For the logout, If a user is logged in and they use the /logout endpoint, I want it to immediately call the handleLogout function and log the user out and reroute to the / endpoint

Here is the code I have and the error:

function App() {

  const [loggedIn, setLoggedIn] = useState(false)
  const [currentUser, setCurrentUser] = useState('')

  function handleLogout() {
    console.log('handle logout')
    axios.post('/api/auth/logout', {
      "username":currentUser.username,
      "password":currentUser.password,
    })
    .then((data) => {
      console.log(data.data)
      setCurrentUser(data.data)
      setLoggedIn(false)
      return(<Navigate to='/' />)
    })
    .catch((err) => {
      console.log(err)
    })
  }

  return (
    <div className="App">
      {/* <ContentContext value={contentContextValue}> */}
        <BrowserRouter>
          <Routes>
              <Route exact path="/" element={loggedIn ? <Feed/> : <Login setLoggedIn={setLoggedIn} setCurrentUser={setCurrentUser}/>} />
              <Route exact path="/login" element={<Login setLoggedIn={setLoggedIn} setCurrentUser={setCurrentUser}/>}/>
              <Route exact path="/signup" element={<Login setLoggedIn={setLoggedIn} setCurrentUser={setCurrentUser}/>}/>
              <Route exact path="/logout" element={loggedIn ? () => {handleLogout()} : <Login/>}/>
            </Routes>
        </BrowserRouter> 
      {/* </ContentContext> */}
    </div>
  );
}

Here is the error:

Warning: Functions are not valid as a React child. This may happen if you return a Component instead of <Component /> from render. Or maybe you meant to call this function rather than return it.