react.js can’t import component

i’m trying to export a component using export default project; and importing using

import project, {toggleCattegories} from './project';

i get the following warning:


./src/components/projecten.js
  Line 2:8:  'project' is defined but never used  no-unused-vars

Search for the keywords to learn more about each warning.
To ignore, add // eslint-disable-next-line to the line before.

project.js code:

import React, { Component } from 'react';
import { Card, CardTitle, CardActions, Button, CardText } from 'react-mdl';

class project extends Component{

constructor(props) {
    super(props)
    this.state = { activeTab: 0 };
}

        toggleCategories() {
    if (this.state.activeTab === 0) {
        return (
            <div className="projects-grid">
                {/*Web*/}
                <Card shadow={5} style={{ minWidth: '450', margin: 'auto' }}>
                    <CardTitle style={{ color: '#000', height: '176px', background: 'url(https://miro.medium.com/max/3600/1*HSisLuifMO6KbLfPOKtLow.jpeg) center / cover' }}></CardTitle>

                    <CardText><h4>Mijn Portfolio</h4>
                        <p>Mijn Portfolio heb ik in ReactJs geschreven. Bekijk het project op github via de button onder deze tekst.</p></CardText>
                    <CardActions border>
                        <Button colored style={{ width: "100%" }}><a href="https://github.com/aminaloui/myportfolio">Github</a></Button>
                    </CardActions>

                </Card>

                <Card shadow={5} style={{ minWidth: '450', margin: 'auto' }}>
                    <CardTitle style={{ color: '#000', height: '176px', background: 'url(https://miro.medium.com/max/3600/1*HSisLuifMO6KbLfPOKtLow.jpeg) center / cover' }}> </CardTitle>
                    <CardText><h4>Boodschappenlijst</h4>
                        <p>In de applicatie meld je je via je google account aan en kun je een boodschappenlijstje opzetten. De objecten worden opgeslagen in een firebase database. </p></CardText>
                    <CardActions border>
                    <Button colored style={{ width: "100%" }}><a href="https://github.com/aminaloui/boodschappen-lijst">Github</a></Button>
                    </CardActions>

                </Card> 
            </div>
        )
    } else if (this.state.activeTab === 1) {
        return (


            <div>{/*Java*/}
                <Card shadow={5} style={{ minWidth: '450', margin: 'auto' }}>
                    <CardTitle style={{ color: '#000', height: '176px', background: 'url(https://www.biernet.nl/images/brouwerij/55296-Bavaria%20logo.jpg) center / cover' }}></CardTitle>

                    <CardText><h4>Bavaria Cashback</h4>
                        <p>Tijdens mijn werkzaamheden bij Acorel Commerce in Alkmaar, heb ik met trots mee mogen werken aan het actieplatform van Bavria. Deze web-app is gebouwd in Java.</p></CardText>
                    <CardActions border>
                        <Button colored style={{ width: "100%" }} ><a href="https://cashback.bavaria.com">Website</a></Button>
                    </CardActions>

                </Card></div>
        )
    }
    else if (this.state.activeTab === 2) {
        return (
            <div>{/*Python*/}
                <Card shadow={5} style={{ minWidth: '450', margin: 'auto' }}>
                    <CardTitle style={{ color: '#000', height: '176px', background: 'url(https://indigo.amsterdam/wp-content/uploads/2017/05/python-django-logo-1024x576.jpg) center / cover' }}></CardTitle>

                    <CardText><h4>Foodify</h4>
                        <p>Foodify is een schoolproject gebouwd voor het vak Praktijkvaardigheden 2. Deze applicatie is gebouwd zodat mensen die te veel hebben gekookt en mensen die niet hebben gekookt elkaar tegemoetkomen. Het doel is om voedselverspilling te voorkomen.</p></CardText>
                    <CardActions border>
                        <Button colored style={{ width: "100%" }} ><a href="https://github.com/aminaloui/Foodify-Praktijk-2-">Github</a></Button>
                    </CardActions>

                </Card></div>
        )
    }
    }  

}

export default project;

projecten.js code:

import React, { Component } from 'react';
import Project, {toggleCattegories} from './project';
import { Tabs, Tab, Grid, Cell, Card, CardTitle, CardActions, Button, CardText } from 'react-mdl';


class Projecten extends Component {
    constructor(props) {
        super(props)
        this.state = { activeTab: 0 };
    }
    
  

    render() {
        return (
            <div className="category-tabs">
                <Tabs activeTab={this.state.activeTab} onChange={(tabId) => this.setState({ activeTab: tabId })} ripple>
                    <Tab>Html / Css/ ReactJS</Tab>
                    <Tab>Java</Tab>
                    <Tab>Python / Django</Tab>
                </Tabs>


                <Grid>
                    <Cell col={6} hidePhone="true" hideTablet="true" >
                        <div className="content"> <toggleCattegories/> </div>

                    </Cell>

                </Grid>

                <Grid>
                    <Cell col={2} phone={6} hideDesktop="true" hideTablet="true" >
                        <div className="content">{this.toggleCategoriesMobile()} </div>

                    </Cell>

                </Grid>
                <Grid>
                    <Cell col={6} tablet={8} hideDesktop="true" hidePhone="true" >
                        <div className="content">{this.toggleCategoriesTablet()} </div>

                    </Cell>

                </Grid>





            </div>
        )
    }
}



export default Projecten;

Thank you for your help!

Angular: how to loop through an array of objects?

I would like to ask, how can I loop through the next object and get the range of hours. For example: In the object I receive the attribute

 {
      slot: '07: 00-08: 00 ',
      start: '2021-12-23T07: 00: 00-06: 00',
      end: '2021-12-23T08: 00: 00-06: 00',
      count: 0,
      available: true,
    }

Where:

slot: is the difference between each hour

end & start: Datetime to compare

available: a status that tells us if that time is enabled

What I need to do is:

1.- Go through the array of objects to compare end and start and thus obtain the time range and paint it with an * ngFor on a button

2.- The hours that are available: false, validate them and disable the button

What I have so far:

Method that it does receives the request from the API and where I store in the variable this.slots the res.

 getAvailability(date: any) {
    this.bookingService.getAffiliateAvailability(this.doctor?.id, this.addressID, date)
      .subscribe(res => {
        if ((this.availableShcedules && this.availableShcedules.length > 0)) {
          this.availability = res;
          const { slots } = this.availability;          
          this.slots = slots;
          console.log(slots);
          this.getSchedulOptions();
          //this.changeDate(slots);
        }
        else {
          this.attentionSchedules
        }
      }, (error => {
        console.error(error)
      }))
  }

Method that compares the range of hours and that range is stored in the variable timeList, then I format that hour with moment.

 getSchedulOptions() {
    let hours: any[] = [];
    this.slots.forEach((s: any) => {
      let start = new Date(s.start);
      let end = new Date(s.end);
      let available = s.available;
      let range = this.getRange(start, end);
      let filteredRange = range.filter((hourAsDate: Date) => {
        return !hours.some(hour => hourAsDate.getHours() === hour.getHours());
      });
     // console.log('probando la hora', moment(start).toDate() < moment().add(30, "m").toDate())
      // console.log('object de la hora', this.clasifyHour(moment(start).toDate()));
      //let disable = available
      if (available == true) {
        hours = hours.concat(filteredRange);
      }
      // console.log('desabilitados', disable);

    })
    console.log('customRange', hours);
    this.timeList = hours.map(hourAsDate => {

      return moment(hourAsDate).format('h:mm a')
    })
  }

  // convierto la hora
  getRange = (start: Date, end: Date) => {
    let startDateInteger = start.getHours();
    let endDateInteger = end.getHours();
    let hours = [];
    for (let i = startDateInteger; i < endDateInteger + 1; i++) {
      let tempDate = new Date(start);
      tempDate.setHours(i);
      hours.push(tempDate);
    }
    return hours;
  }

hours console, res of filter the object

HTML that receives the timeList variable

<div class="col-12 mx-0 mx-lg-4">
  <div class="row">
    <div class="col-12 px-4">

      <div *ngIf="selectedDate" data-aos="fade-up" data-aos-anchor-placement="top-bottom" class="DateContainer py-2 d-flex">
        <!-- Slider main container -->
        <mat-icon class="swiperLeft m-auto">chevron_left</mat-icon>
        <swiper class="TimeContainer" [config]='swiperConfig' (swiper)="onSwiper($event)" (slideChange)="onSlideChange()">
          <ng-template swiperSlide class="SwiperItem text-center" *ngFor="let time of timeList; let i = index">

            <button *ngIf="selectedTime == time" mat-flat-button color='primary' class="SelectedTime">{{time}}
                                                </button>
            <button *ngIf="selectedTime != time" mat-stroked-button (click)="setTime(time)">{{time}}
                                                </button>
          </ng-template>
        </swiper>

        <mat-icon class="swiperRight m-auto">chevron_right</mat-icon>
      </div>
    </div>
  </div>
</div>

I would then need to go through the arrangement and validate if there are any with available: false, disable the button

Please help me!

NgFor of timeList

When I am adding elements to an array, only the last element is added to the array? I cant find out what is wrong in the closure

const data = require(‘../content/data’)

function randomize() {
const ds_size = Math.floor(Math.random() * 500) + 50 //Generate no of objects in stream
let name_index = 0
let origin_city_index = 0
let destination_city_index = 0
let org_message = {
name: ”,
origin: ”,
destination: ”
}
let ds = [];
return function getDs() {
for(let i = 0; i< ds_size; i++) {
name_index = Math.floor(Math.random() * data.names.length)
origin_city_index = Math.floor(Math.random() * data.cities.length)
destination_city_index = Math.floor(Math.random() * data.cities.length)
org_message.name = data.names[name_index]
org_message.origin = data.cities[origin_city_index]
org_message.destination = data.destination[destination_city_index]
ds.push(org_message)
}
return ds
}
}

module.exports = {randomize}

Why monao editor does a request on /v/vs/language/typescript/tsWorker.js while it must be /vs/language/

I want to add monaco editor on my website but when i try this code :

<script src="https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.32.0-dev.20211222/min/vs/loader.js" integrity="sha512-9fANEu2oim+NnACLlgBgJAgG3FMQNOIifCcsxzqDAVbHSTtiFECb+pQf7G2BYwxwYkfPrNtULNCvy4DHyFzPoQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script>
    require.config({ paths: { vs: 'https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.32.0-dev.20211222/min/vs/' } });
    require(['vs/editor/editor.main'], function () {
        let editor = monaco.editor.create(document.getElementById('container'), {
            value: ['function x() {', 'tconsole.log("Hello world!");', '}'].join('n'),
            language: 'javascript',
            theme: 'vs-dark'
        });
    });
</script>

I have an error in the developer console: Loading the script at the address" https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.32.0-dev.20211222/min/v/ vs / language / typescript / tsWorker.js "with importScripts () was blocked due to a forbidden MIME type (" text / html ") .

I checked the url in cdnjs.com and found this error: min / v / vs / there is no that but / min / vs

I think this is not an error provided by the contributor of monaco editor but I do not understand what my error is

Same item is being rendered despite of different query string in React ( Next.js )

Please, first look at my code.

I made this up to present my code clearly. There might be some misspell. please be understandable!

//parent component

<Component nickname={nickname} />
//child component

//nickname is a prop of dynamic routing.

const test = ({nickname}) => {


const [number, setNumber] = useState('');
const [array, setArray] = useState([]);

const getNumber = () => {
 const url = '/api/number';
 const data = {
     nickname = nickname
  }
 axios.post(url, data)
 .then((res) => {
    setNumber(res.NUMBER)
 })
};

useEffect(() => {
  getNumber()
}, [nickname]) //when nickname (dynamic routing url) changes, the statement executes.

const getItem = async () => {
  const url = '/api/get';
  const data = {
     id : number
  };
  await axios.get(url, data)
  .then((res) => {
     setArray([...array, res])
  })
};

useEffect(() => {
  getItem()
}, [])

return (

<>
<div>
  {
   array.map((arr) => (
      {arr.name}
   ))
  }
</div>

</>

)
}

From this code, I’m having trouble getting different items.

Whenever I enter a different URL, array should be changed as I give different number in

const getItem = async () => {
  const url = '/api/get';
  const data = {
     id : number
  };
  await axios.get(url, data)
  .then((res) => {
     setArray([...array, res])
  })
};

here.

But seems there is no change even I enter a different URL.

However, when I directly edit the number state, It changes appropriately.

I don’t know what is going on, and looking for some wisdom.

Which data types can be toString?

“The undefined is not an object, so there is no toString.”How do you understand this sentence?Is it that only Object can toString and none of the other six data types can toString?Which data types can be toString?

Cannot read properties of undefined (reading ‘get’)

I am trying to do a command handler, when I start the discord bot it acts normally, until I use some command

console error

        const command = client.commands.get(commandName) || client.commands.find(cmd => cmd.aliases && cmd.aliases.includes(commandName));
                                        ^

TypeError: Cannot read properties of undefined (reading 'get')

index.js

/////////////////////////////Danger Zone/////////////////////////////

client.on('messageCreate', message => {
    if (message.content.startsWith(prefix)) {
        const args = message.content.slice(prefix.length).split(/ +/);
        const commandName = args.shift().toLowerCase();
        const command = client.commands.get(commandName) || client.commands.find(cmd => cmd.aliases && cmd.aliases.includes(commandName));
        if (!command) return;
        try {
            command.execute(message, args);
        } catch (error) {
            console.error(error);
            message.reply('there was an error trying to execute that command!');
        }
    }
});

/////////////////////////////Danger Zone/////////////////////////////

ping.js

/////////////////////////////Danger Zone/////////////////////////////

    const { SlashCommandBuilder } = require('@discordjs/builders');

module.exports = {
    data: new SlashCommandBuilder()
        .setName('ping')
        .setDescription('Replies with Pong!'),
    async execute(interaction) {
        await interaction.reply('Pong!');
    },
};

/////////////////////////////Danger Zone/////////////////////////////

How to change x labels to plain text, and scale Y to logarithmics in D3 js

Hi i figured out how to add log labels at Y axis axis but cant make chart line scale log, and i dont really know how to make X axis labels plain text instead of converting it to date

If i just change scaleLinear to scaleLog chart line dissapear

Also removing const parseTime = d3.timeParse(‘%Y/%m/%d’); and change parseTime(val.date) just to val.date, and changing scaleTime to scaleOrdinal does not work as i would

Sorry for asking but cant findout how this pluggin works.
using D3 7.2.1 and JQ 3.5.1

(function (d3){
        const lineChartData = [
        {
            currency: "data",
            values: [
            {
                date: "2018/01/01",
                close: 0
            },
            {
                date: "2018/02/01",
                close: 5
            },
            {
                date: "2018/03/01",
                close: 10 
            },
            {
                date: "2018/04/01",
                close: 50 
            },
            {
                date: "2018/05/01",
                close: 100 
            },
            {
                date: "2018/06/01",
                close: 500 
            },
            {
                date: "2018/07/01",
                close: 1000 
            },
            {
                date: "2018/08/01",
                close: 5000 
            },
            {
                date: "2018/09/01",
                close: 10000 
            },
            ]
        }
        ];
    
        const margin = {
        top: 20,
        bottom: 20,
        left: 50,
        right: 20
        };
    
        const width = 400 - margin.left - margin.right;
        const height = 300 - margin.top - margin.bottom;
        
        const createGradient = select => {
        const gradient = select
            .select('defs')
            .append('linearGradient')
                .attr('id', 'gradient')
                .attr('x1', '0%')
                .attr('y1', '100%')
                .attr('x2', '0%')
                .attr('y2', '0%');

        gradient
                .append('stop')
                .attr('offset', '0%')
                .attr('style', 'stop-color:#FF6500; stop-opacity:0');

        gradient
            .append('stop')
            .attr('offset', '100%')
            .attr('style', 'stop-color:#FF6500; stop-opacity: 1');
        }
        
        const createGlowFilter = select => {
        const filter = select
            .select('defs')
            .append('filter')
                .attr('id', 'glow')
    
        //stdDeviation is px count for make blur around main chart line
        filter
            .append('feGaussianBlur')
            .attr('stdDeviation', '0')
            .attr('result', 'coloredBlur');
        
        const femerge = filter
            .append('feMerge');
        
        femerge
            .append('feMergeNode')
            .attr('in', 'coloredBlur');
        femerge
            .append('feMergeNode')
            .attr('in', 'SourceGraphic');
        }
    
        const svg = d3.select('#line-chart')
        .append('svg')
            .attr('width', 700 + margin.left + margin.right)
            .attr('height', 300 + margin.top + margin.bottom)
        .append('g')
            .attr('transform', `translate(${margin.left}, ${margin.top})`);
        
        svg.append('defs');
        svg.call(createGradient);
        svg.call(createGlowFilter);
    
        const parseTime = d3.timeParse('%Y/%m/%d');
        
        const parsedData = lineChartData.map(company => ({
        ticker: company.ticker,
        values: company.values.map(val => ({
            close: val.close,
            date: parseTime(val.date)
        }))
        }));
    
        const xScale = d3.scaleTime()
        .domain([
            d3.min(parsedData, d => d3.min(d.values, v => v.date)),
            d3.max(parsedData, d => d3.max(d.values, v => v.date))
        ])
        .range([0, width]);

        const yScale = d3.scaleLinear()
        .domain([
            d3.min(parsedData, d => d3.min(d.values, v => v.close)),
            d3.max(parsedData, d => d3.max(d.values, v => v.close))
        ])
        .range([height, 0]);
        
        const line = d3.line()
        .x(d => xScale(d.date))
        .y(d => yScale(d.close))
        .curve(d3.curveCatmullRom.alpha(0.5));
        
        svg.selectAll('.line')
        .data(parsedData)
        .enter()
        .append('path')
            .attr('d', d => {
            const lineValues = line(d.values).slice(1);
            const splitedValues = lineValues.split(',');
        
            return `M0,${height},${lineValues},l0,${height - splitedValues[splitedValues.length - 1]}`
            })
            .style('fill', 'url(#gradient)')
        
        svg.selectAll('.line')
        .data(parsedData)
        .enter()
        .append('path')
            .attr('d', d => line(d.values))
            .attr('stroke-width', '2')
            .style('fill', 'none')
            .style('filter', 'url(#glow)')
            .attr('stroke', '#FF6500');

        const tick = svg.append('g')
        .attr('transform', `translate(0, ${height})`)
        .call(d3.axisBottom(xScale).ticks(9))
        .selectAll('.tick')
        .style('transition', '.2s');
    
        //Y dashes
        //stroke color of line in background
        //stroke-dasharray
        //first paramter is length
        //second parameter is space between
        tick
        .selectAll('line')
            .attr('stroke-dasharray', `4, 7`)
            .attr('stroke', '#5E779B')
            .attr('y2', `-${height}px`)
        tick
        .append('rect')
            .attr('width', `${(width / 12) + 10}px`)
            .attr('x', `-${width / 24 + 5}px`)
            .attr('y', `-${height}px`)
            .attr('height', `${height + 30}px`)
            .style('fill', 'transparent');
            
        svg.selectAll('.tick')
        .append('circle')
            .attr('r', '5px')
            .style('fill', '#ffffff')
            .style('stroke', '#FF6500')
            .attr('cy', (x, i) => - height + yScale(parsedData[0].values[i].close));


        svg.select('.domain')
        .attr('stroke', '#5E779B')
        .attr('stroke-dasharray', `4, 7`)

        var yscale = d3.scaleLog()
            .domain([1, 100000])
                        .nice()
            .range([height - 10, -10]);

        var y_axis = d3.axisLeft(yscale);

        y_axis.ticks(5);
  
        svg.append("g")
            .call(d3.axisLeft(xScale).ticks(5))
            .attr("transform", "translate(0, 10)")
            .attr('stroke', '#5E779B')
            .attr('stroke-dasharray', `4, 7`)
            .call(y_axis)
    })
    (d3);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

<body>
    <div id="line-chart"></div>
</body>

Unzipping 3MF Files in Javascript

I am new to javascript and i wanted to achieve a task of unzipping 3mf files for my project. Here is the below code which i am trying.

LocalConverter.prototype.unzip3MFTextures = async function(fileToUnpack){
    const self = this;
    return new Promise(function(resolve, reject) {
        yauzl.open(fileToUnpack, function(err, zipfile) {
            if (err) throw err;
            zipfile.on("error", function(err) {
            throw err;
            });
            zipfile.on("entry", function(entry) {
            console.log(entry);
            console.log(entry.getLastModDate());
            if (//$/.exec(entry)) return;
            zipfile.openReadStream(entry, function(err, readStream) {
                if (err) throw err;
                readStream.pipe(process.stdout);
            });
            });
        }); 
    });
}

I am not able to extract the files in the 3MF file. Can anyone please suggest me a way to fix this?

Gettting “Uncaught TypeError: Cannot read properties of undefined (reading ‘map’)”

I have my app component

import './App.css';
import Header from './components/Header'
import { useState } from 'react'
import Tasks from './components/Tasks';


const App = ()=> {
  const [tasks, setTasks] = useState([
    {
        id:1,
        text: 'Task 1',
        day:'every',
        reminder: true
    },
    {
        id:2,
        text: 'Task 2',
        day:'every',
        reminder: true
    },
    {
        id:3,
        text: 'Task 3',
        day:'every',
        reminder: false
    }
]);
  return (
    <div className="App">
      <Header/>
      <Tasks tasks={tasks}/>
    </div>
  );
}

export default App;

and then my Tasks component

const Tasks = ({ tasks }) => {
  return (
    <>
      {tasks.map((task) => (
        <h3 key={task.id}>{task.text}</h3>
      ))}
    </>
  )
}
export default Tasks;

For some reason, it does not seem to like me passing my destructured tasks prop into my Tasks component. I tried adding prop types for Tasks and passing props as a parameter instead of tasks and mapping props.tasks but it still gave me the same error.

Prevent date picker from scrolling with page

I am making a react app which has datepicker made up of antd

Simple index.js code:

import React from "react";
import ReactDOM from "react-dom";
import { DatePicker } from "antd";
import "antd/dist/antd.css";
import "./index.css";

ReactDOM.render(
  <div className="App">
    <h1>Select date-picker scroll bug.</h1>
    <div
      style={{ marginTop: "16px", width: 500, overflow: "scroll", height: 400 }}
    >
      <DatePicker />
      <div style={{ minHeight: 500 }}></div>
    </div>
  </div>,
  document.getElementById("root")
);

Working Example:

Edit antd reproduction template (forked)

To Reproduce: If user clicks on the input, datepicker displayed but when we try to scroll down, the datepicker also get scrolled along with the page.

Expected Result: Datepicker should not get scrolled and it needs to be under the input box.

Any help would be highly appreciable. Thanks in advance.

How to convert currency using native Shopify converter?

As the title states, I’m using Shopify. I’m able to convert the currency from USD to another, but the currency it’s self is still 20 in value, if it’s $20 USD it’s 20 in any other currency.

Shopify.formatMoney(2000)

I also found this in my theme.js

Currency.moneyFormats[Shopify.currency.active]["money_format"]

But this returns

{{amount}} USD

And I’m not really sure where that is assigned?

How to display base64 image in React Js?

I am receiving the Image as Base64 from the server. I want to decode and display the image. How do I decode base64 to Image ? I dont want to directly paste the base64 string into the image source as its taking alot of time to load the image and also not supported by few browsers.

Below is the code :

// Takes base64 string & returns Image
function decodeBase64Image(base64_string) { };

var Image = decodeBase64Image(base64_string);

<img src={Image} />