inserting elements from an array to a div’s innerHTML using forEach()

I m basically trying to first clear the form div by saying form.innerHTML = ''. Then when i try to insert one by one the elements from an array back to the form div using forEach() on the array, it just sets the innerHTML to the last element from that array.
Here’s my javascript code :

 form.innerHTML = '';

    userCorrectAnswers.forEach(e => {
        let cA = e.innerHTML;
        form.innerHTML = cA;
    })

Need to know how can i add all the elements from that array to the innerHTML of the form.

Passing variable to other pages in react

I have to make global variable to be taken for all pages in the reactJs application. It is named as ‘city’ where it changes every time I am using useState of reactJs. The city is only changed in Mainpage of the react site.
When I change the city in Mainpage and direct it to other pages then the changed value of the city is not taken. It remains the default that I declared at app.js. I checked it by printing the city in the console in app.js and it changes every time when I change it in MainPage which is correct, but when I direct it to other pages the default value of the city i.e, ‘Select city’ is taken.
I use the functional component. The image of the declaration of the variable and routing is given in the image.
Mainpage is changing the city in app.js but it is not forwarded to other pages. The default value is taken for it.
I want that whenever the value of the city is changed in the MainPage the effect will show in the app.js, which is working, and also to the other pages when I go to them just like, ‘https://www.nobroker.in/home-services’, them. But the changes are not reflected to other pages.
I am using tag to redirect the window to other pages.

The code of app.js is:

function App() {

const [city, setCity] =useState(“Select City”)

const handleData = (data) => {
setCity(data)
}
console.log(city);

return (

  {/* home page  */}
  <Route exact path='/home-services' element={<HouseDeckHomeServicesMainPage city={city} setCity={setCity} handleData={handleData} />} />
  <Route exact path='/' element={<HouseDeckHomeServicesMainPage city={city} setCity={setCity} handleData={handleData} />} />
  <Route exact path='/home' element={<HouseDeckHomeServicesMainPage city={city} setCity={setCity} handleData={handleData} />} />

  {/* footer pages  */}
  <Route exact path='/home-services/terms-and-conditions' element={<HouseDeckHomeServicesTC/>} />
  <Route exact path='/home-services/privacy-policy' element={<HouseDeckHomeServicesPrivacy/>} />
  <Route exact path='/home-services/return-exchange-and-refund' element={<HouseDeckHomeServicesPrivacy/>} />
  <Route exact path='/home-services/faqs' element={<HouseDeckHomeServicesFAQpage />} />

  {/* services pages  */}
  <Route exact path='/home-services/painting' element={<HouseDeckHomeServicesPainting city={city} setCity={setCity} handleData={handleData} />} />
  <Route exact path='/home-services/cleaning' element={<HouseDeckHomeServicesCleaning city={city} setCity={setCity} handleData={handleData} />} />
  <Route exact path='/home-services/home-sanitization' element={<HouseDeckHomeServicesSanitization city={city} setCity={setCity} handleData={handleData} />} />
  <Route exact path='/home-services/ac-repair' element={<HouseDeckHomeServicesACRepair city={city} setCity={setCity} handleData={handleData} />} />
  <Route exact path='/home-services/electrician' element={<HouseDeckHomeServicesElectrician city={city} setCity={setCity} handleData={handleData} />} />
  <Route exact path='/home-services/carpentary' element={<HouseDeckHomeServicesCarpentary city={city} setCity={setCity} handleData={handleData} />} />
  <Route exact path='/home-services/plumbing' element={<HouseDeckHomeServicesPlumbing city={city} setCity={setCity} handleData={handleData} />} />

  {/* 404 page  */}
  <Route exact path='*' element={<HouseDeckHomeServicesNotFound city={city} />} />
</Routes>
</BrowserRouter>

);
}

enter code here

please help.

how to use variables conditionally in styled components

I am trying to conditionally change the UI of my component in styled components, but I found myself repeating myself a lot.
this is what is happening right now:

color: ${props => (props.isProductPage ? color('white') : 'reset')};
background-color: ${props =>
  props.isProductPage ? color('primary', 'main') : 'reset'};
font-size: ${props => (props.isProductPage ? '1.4rem' : 'reset')};
font-weight: ${props => (props.isProductPage ? '400' : 'reset')};

but I want to have all these in a variable and import that variable conditionally, but I could not find out what am I doing wrong. This is what I am looking for.

const ProductPageAddToCard = `
color: ${color('primary')};
background: ${color('primary', 'main')};
font-size: ${textSize('medium')};
font-weight: ${textWeight('medium')}
`;

export const StyledAddToCardWrapper = Styled.div`
 button {
  ${props => (props.isProductPage ? ProductPageAddToCard : '')}
 }
`

Thanks in advance

FlatList conditional rendering if {user === owner || gues}

In my Applikation I render a Expo FlatList to show created Events.

List Preview

If the user has created or joined this event, he should be able to see the images. If not, they should be hidden.

I would now store the creator and the guests in the database and would have to compare this with the currentUser from the Firebase Auth beforehand.

However, I face the problem that I can’t tell the FlatList which items should be rendered and which shouldn’t.

Does anyone knows a solution for conditional render a FlatList?

Fullcode

import React, { Component } from 'react';
import { FlatList, Box,  } from "native-base";
import { StyleSheet } from 'react-native'
import EventCard from "./EventCard.js";
import { collection, getDocs } from 'firebase/firestore';
import { firestore, auth } from '../firebase.js'
import { getStorage } from "firebase/storage"

export default class Events extends Component {

    constructor(props) {
        super(props);
        this.currentUser = auth.currentUser
        this.navigation = this.props.navigation
        this.storage = getStorage()
        this.querySnapshot = getDocs(collection(firestore, 'events'));
        this.state = {
            isLoading: true,
            fetch: false,
            eventData: {
                adress: '',
                hosts: '',
                description: '',
                eventtitle: '',
                invitecode: '',
                key: '',
                timestamp: '',
                owner: '',
            }
        }
    }

    componentDidMount() {
        this.loadEventsFromFirebase()

    }

    //  reload on pull down
    onRefresh() {
        this.setState({
            fetch: true
        });
        this.loadEventsFromFirebase()
    }

    loadEventsFromFirebase() {
        let data = []
        this.querySnapshot.then(querySnapshot => {
            querySnapshot.docs.map(doc => {
                data.push(doc.data())
            })
            this.setState({
                eventData: data,
                fetch: false,
            });
        });

    }

    render() {

        return (
            <Box style={styles.container} _dark={{ bg: "blueGray.900" }} _light={{ bg: "blueGray.50" }}>
                <FlatList
                    showsVerticalScrollIndicator={false}
                    onRefresh={() => this.onRefresh()}
                    refreshing={this.state.fetch}
                    data={this.state.eventData}
                    keyExtractor={item => item.key}
                    renderItem={({ item }) => (<EventCard key={Date.now()} eventData={item} />
                    )}
                />
            </Box>
        )
    }
}

const styles = StyleSheet.create({
    container: {
        alignSelf: 'stretch',
        alignItems: 'center'
    },
})

Calculating max and avg values from two arrays

I am trying to use two arrays to calculate max value and average values to create key/value object.
Here are the two arrays

const products = ["car", "car", "motorcycle", "motorcycle"] // key
const prices =[2000, 1500, 800, 900] // value

desire outcome - 
{"car" : {max: 2000, average: 1750}, 
"motorcycle":{max: 900, average: 850} }

It will be great if ES6 iterators like reduce/map and etc can be used for solution.

Thank you for help!

Is there anything like i want to add my navbar on every website using my own chrome extension? [closed]

I’m building one chrome extension with Reactjs and it’s work is to show stock details on top of every website and it’s position should be fixed, but I’m facing one issue that is my extension navbar is overlapping website navbar.

I want to add my custom navbar then website own page.

I have used document.body.appendChild() also added position: fixed
But not working.

Recent grad revisiting a 2021 plain JS app project. Issues running front end server with Webpack [closed]

I graduated a couple weeks ago with a Certificate in Full Stack Development. Post graduation, we’re instructed to revisit and revise older projects. One of which, I accidentally deleted package.json files as well as all node.js files. Don’t ask me how. Ashamed to say if a recruiter asked me to demonstrate booting up a vanilla JS server app, I’d be in trouble. If he/she asked me about file source control with Github, I’d be in deep trouble as well. Most commits have disappeared. Unfortunately, these topics were briefly mentioned within the course curriculum and now I’m having to go back and research. I suppose Ive been so accustomed to react and rails setup that I forgot how to start up a plain server without either frameworks. With each Youtube tutorial and package.json configuration, I grow more confused as to how to get things back up and running. To be more specific, it seems my updated webpack configurations do not permit me to render code to the browser from localhost8080. The console error says GET http://localhost:8080/ 404 (Not Found) I do not know where to begin to resolve this issue. Still lost after hours of tutorial videos. Any help is gladly appreciated.
Git Repository: https://github.com/jasonronalddavis/ManyProjectsFrontend
Terminal error log:

ERROR in ./src/style.css (./node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[1].use[1]!./src/style.css)
Module build failed (from ./node_modules/css-loader/dist/cjs.js):
ValidationError: Invalid options object. CSS Loader has been initialized using an options object that does not match the API schema.
 - options has an unknown property 'minimize'. These properties are valid:
   object { url?, import?, modules?, sourceMap?, importLoaders?, esModule?, exportType? }
    at validate (/Users/jasondavis/Flatiron/code/ManyProjectsFrontEnd/node_modules/schema-utils/dist/validate.js:105:11)
    at Object.getOptions (/Users/jasondavis/Flatiron/code/ManyProjectsFrontEnd/node_modules/webpack/lib/NormalModule.js:585:19)
    at Object.loader (/Users/jasondavis/Flatiron/code/ManyProjectsFrontEnd/node_modules/css-loader/dist/index.js:31:27)
 @ ./src/style.css 8:6-127 22:17-24 26:7-21 58:25-39 59:36-47 59:50-64 63:6-73:7 64:54-65 64:68-82 70:42-53 70:56-70 72:21-28 83:0-97 83:0-97 84:22-29 84:33-47 84:50-64 61:4-74:5

webpack 5.70.0 compiled with 1 error in 17776 ms

chart.js scale xaxis with date, strange renderer

Hi i got this renderer with my config on chart.js, i dont understand why i got

enter image description here

this is the version of chart.js

/*!
 * Chart.js
 * http://chartjs.org/
 * Version: 2.7.1
 *
 * Copyright 2017 Nick Downie
 * Released under the MIT license
 * https://github.com/chartjs/Chart.js/blob/master/LICENSE.md
 */

i generate my chart with this function and i dont understand how to fix my problem
thanks for your help

new Chart(document.getElementById("line-chart"), {
        type: 'line',
        data: {
            labels: datadate,
            datasets: [{ 
                data: datavalue,
                label: "Value array",
                borderColor: "#3e95cd",
                pointRadius: 3,
                pointHoverRadius: 3,
                fill: false
                }
            ]
        },
        options: {
                title: {
                display: true,
                text: 'returned value'
                },
                
                scales: {
                    yAxes: [{
                        ticks: {
                            beginAtZero: false
                        }
                    }],
                    xAxes: [ {
                        type: 'time',
                       time: {
                        min: Math.min.apply(null, datadate),
                        max: Math.max.apply(null, datadate)
                       }
                    }],
                },
                responsive: true
        }
    });

Why do my filters work separately from each other?

I have two selections that are supposed to filter data, they work but separately, how do I make them filter data together?

When I click on the second select, it resets the data from the first one. They filter the same data array, so the result is new all the time, I don’t understand how to filter an already filtered array

How do I make a joint filter?

 //filter data
  const [allData, setAllData] = useState<ICompanie[]>(companiesData);

  // status filter
  const handleStatusFilter = (status: string): void => {
    const filterData = companiesData.filter((item) => {
      if (item.status === status) {
        return item;
      }
    });

    setAllData(filterData);
  };

  // category filter
  const handleCategoriesFilter = (category: string): void => {
    const filterData = companiesData.filter((item) => {
      if (item.category === category) {
        return item;
      }
    });

    setAllData(filterData);
  };

How to encode a remote image into base64 string?

I have an image url

url = "https://images.unsplash.com/photo-1511884642898-4c92249e20b6?ixlib=rb- 
1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1470&q=80"

Can anyone tell me please how can I encode this remote image into base64 string in javascript…

Angular Modal Error-cannot read properties of undefined (reading ‘classList’) –

I am trying to call modal from my cardetails page
normla modals didnt fit for me and i used angular ngb bootstrap modal
Modal opens when i click open button

BUT
it gives error no the console.
error at console: picture

Actually there are two modals at different pages and they have different component ts code but they give same error.
IT is not related with html code .

this is cardetails.html where is modal .open button is located(at the bottom)

<div class="card" style="width:100%;margin-top: 20px;">

  <div class="row"style="max-height: 80%;">

  </div>
    <carousel  style="height:95%; width: 100%;" >
      <slide *ngFor="let imagePath of carImagePaths; let index=index" >
        <img [src]="imageUrl+imagePath" alt="image slide"class="image-fluid" style=" height:400px;width: 100%; object-fit: cover">
    
        <div class="carousel-caption">
          <h4>Görsel: {{index+1}} </h4>
          <p></p>
        </div>
      </slide>
    </carousel>
  


      <!-- car detail sayfası araç detay bilgileiri -->
      <div *ngFor="let car of cars" class="card-body">
        <div class="card-body detailsFontInfo">

            <h5 class="card-title">
            {{ car?.brandName }} || {{ car?.modelName }}
            </h5>
            
        </div>
    
        <ul class="list-group list-group-flush  detailsFontInfo">
            <li class="list-group-item"><b>Renk :</b> {{ car?.colorName }}</li>
            
            <li class="list-group-item  detailsFontInfo"> <b>Model Yılı :</b> {{ car?.modelYear }}</li>

            <li class="list-group-item  detailsFontInfo"> <b>Günlük Fiyat :</b> {{ car?.dailyPrice | currency: "USD":true:"1.2-2" }}</li>

            <li class="list-group-item  detailsFontInfo"><b>Açıklama:</b> {{ car?.description }}</li>
            <li class="list-group-item  detailsFontInfo"><b>Kira Durumu :</b> {{ car?.isRentable ? "Uygun Değil" : "Müsait" }}</li>


           
            <!-- <b>Status : </b> {{ carDetail?.isRentable ? "Available" : "Not Available" }} -->
            
        </ul>
    </div>
    <!-- alt butonlar -->
    <div style="margin-bottom: 4%;">
      <div class="row">
        <div class="btn-goback col-md-2 offset-md-8">
          <button style="width: 100%;" routerLink="/cars" type="button" class="btn btn-outline-dark">
            Geri Dön
          </button>
        </div>


          <!-- giriş yapılmamışsa giriş yap -->
        <div class="col-md-2"*ngIf="!isAuthenticated()">
            


            <!-- burada modal çıksın ve desin ki kiralayabilmek için kayıt olun veya giriş yapın -->
            <button (click)="openLoginModal()" style="width: 100%;" type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#carDetailIsAuthModal">
              Kirala
            </button>
        </div>


        <!-- giriş yapılmamışsa rentala git -->

        <div class="col-md-2" *ngIf="isAuthenticated()">
          <!-- eğer giriş yapılı ise kirala butonuna bassın RENT MODAL GELSİN  -->

          <button (click)="openRentalModal()" style="width: 100%;" type="button" class="btn btn-success" data-bs-toggle="modal" data-bs-target="#carDetailsRentalModal">
            Kirala
            
          </button>
          
       </div>

      </div>
    

      
</div>

this is cardetails.ts

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { CarDetails } from 'src/app/models/carDetails';
import { CarImage } from 'src/app/models/carImage';
import { CarImageService } from 'src/app/services/car-image.service';
import { CarService } from 'src/app/services/car.service';
import { NgbActiveModal, NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { NonNullAssert } from '@angular/compiler';
import { LoginComponent } from '../login/login.component';
import { RentalComponent } from '../rental/rental.component';
import { RentalService } from 'src/app/services/rental.service';

@Component({
  selector: 'app-cardetail',
  templateUrl: './cardetail.component.html',
  styleUrls: ['./cardetail.component.css']
})
export class CardetailComponent implements OnInit {
  //carDetail:CarDetails[]= [];
  cars: CarDetails[] = [];
  carImagePaths:string[] = [];
  carDetail: CarDetails;
  dataLoaded = false;
  imageUrl:string="https://localhost:44396/Uploads/images/"
  //--for rental
  
 
  
  
  carImages:CarImage[]=[];//slider için

  constructor(private carImageService: CarImageService,
    private carService: CarService,
    private activatedRoute: ActivatedRoute,
    public modalService:NgbModal,
    private rentalService:RentalService,
    ) { }

  ngOnInit(): void {


    this.activatedRoute.params.subscribe(params => {//car id verilirse ki arabaya tiklayinca verilmis olur: icerdeki emthodlari calistir

      if(params['carId']){
          this.getCarsDetailsByCarId(params['carId'])
         // this.getImagesByCarId(params['carId'])

        }
    })

    
  }

 
  




  getCarsDetailsByCarId(carId: number){//details sayfamızdaki araç detaylarını çekiyor
    this.carService.getCarsDetailsByCarId(carId).subscribe((response)=>{
      this.cars=response.data
      this.carDetail = response.data[0];//sıfırıncı eement bilgilerin olduğu kısım,sonra mesaj felan geliyor
      
      this.carImagePaths=this.carDetail.imagePath
      this.dataLoaded = true;

    })
  }

  // geçici olarak login li isAuthenticated:true/false mutlaka sil bunu sonra
  isAuthenticated(){
    return false
  }
    
  openLoginModal() {//LOGİN MODAL ı açar (cardetailhtmldeki buton)
    let modalRef=this.modalService.open(LoginComponent)
  }
  openRentalModal(){
    let modalRef= this.modalService.open(RentalComponent)
    //buraya tıkalyınca hem rentala gitmeli
    
  

  }
  
  

  
}

MODALS HTML İS EMTY OR FULL DOESNT MATTER SAME ERROR

MODALS TS

import { Component, OnInit } from '@angular/core';
import { NgbActiveModal, NgbModal } from '@ng-bootstrap/ng-bootstrap';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {

  constructor(public modal:NgbActiveModal) { }

  ngOnInit(): void {
  }

}

Any ideas might help