Call and Display React Components on an element’s id using onClick Events

I really need your help here, as I am new learning React. Meanwhile, this question has not yet been asked and the issue is not yet raised.
I am trying to call a to display on a element id using document.getElementById(‘disp’).innerHTML. However, I am having a [OBJECT OBJECT] response as the result if I use the component as a variable, and a gibberish of JSX webhook codes if I use it as a
Please help me with the following codes below and the screenshots explains my point.

injex.js

import ReactDOM from "react-dom/client";
import React from 'react'
import Nav from './Navigation'    
import './styles.css'
import Logo from './logo1.png';

const Template = () => {
  return (
    <>
      <section className='container-fluid'>
        <header className='row bg-dark' style={ {height: '100px' }}>
          <HeaderLogo />
          <HeaderLeftColumn />
          <HeaderRightColumn />
        </header>

        <sesion className='container-fluid'>
          <section className="row">
            <div className="col-sm col-mr col-md col-lg col-xl">
              <HeaderMarquee />
            </div>
          </section>
        </sesion>
        <article className='container-fluid' id='disp' style={ {borderStyle: 'outset', borderColor: 'silver', borderRadius: '5px'} }>
          <MainBody />
        </article>

        <div className='container-fluid'>
          <div className='container'>
            <div id='statusBar' className='alert'>...</div>
          </div>
        </div>
      </section>
    </>
  )
}  

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Template />);

Navigation.js

import React from 'react'
import "bootstrap/dist/css/bootstrap.min.css"
import './styles.css'
import CreateSchoolCategory from './components/createschoolcategory'

//this code works well when a text is just assigned to the div element
const showPaymentAPIPage = () => { 
    { document.getElementById('disp').innerHTML = `Payment API Page` }
}

enter image description here

//calling it as a component will return [object object] as response on the element id
const showCreateSchoolCategory = () => {
     {{ document.getElementById('disp').innerHTML = <CreateSchoolCategory /> } }
}

enter image description here

//calling it as a variable will return a gibberish of JSX interpreted codes on the element id.
const showCreateSchoolCategory = () => {
     {{ document.getElementById('disp').innerHTML = CreateSchoolCategory  } }
}

enter image description here

const Nav = () => {
  return (
    <>
       {/* <section className='text-danger'> <TestPage /> </section>  */}

      <nav class="navbar navbar-expand-lg navbar-dark bg-dark">  
        <button className="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
            <span className="navbar-toggler-icon"></span>
        </button>
        <div className="collapse navbar-collapse" id="navbarSupportedContent">
            <ul className="navbar-nav mr-auto">
                <li className="nav-item dropdown">
                    <a className="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                        Main | Data Settings
                    </a>
                    <div className="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
                        <a className="dropdown-item listFont" href="#" onClick={showPaymentAPIPage}>Payment API</a>
                        <a className="dropdown-item listFont" href="#" onClick={showCreateSchoolCategory}> Create School Categories</a>                                                       
                    </div>
                </li>
            </ul>
        </div>
      </nav>      
    </>
  )
};

export default Nav

createschoolcategory.js

import React, { Component } from 'react'
function headerText() {
    // const url = window.location.href;
    // if(url.includes('create-school-categories') === true){
    //     return document.getElementById('header').innerHTML = `Create New School Category`;
    // }
    // return document.getElementById('header').innerHTML = '';
    return document.getElementById('header').innerHTML = `Create New Teacher Category`;
const CreateSchoolCategory = () => {    
    
    headerText() 
    return (
        <>
            <div className='container' id="disp">
                <div className='row'>
                    <div className='col-sm col-md col-lg col-xl'>
                        <h5 className='text-info'>Create School Categories</h5>
                    </div>
                </div>                    
            </div>                
        </>
    )        
}

export default CreateSchoolCategory

Please help me!

weird problem. adding 1 to 0 doesnt do anything

Okay, i dont even know how to describe this problem but i will try my best. you can find all my code at the bottom

 const scores = { 0: 0, 1: 0, 2: 0, 3: 0, 4:0, 5:0, 6:0 }
 const [point, setPoint] = useState(scores)

so i setstate to an array, later on i am calling it with a button

 <button onClick ={()=> setPoint (point[selected] +1 )}>Vote</button>
 <button onClick={()=> setSelected(Math.floor(Math.random()* anecdotes.length ))}>next anecdotes</button>
 {scores[selected]}

at first it should the value at the [selected] to be at 0, but whenever i press on the vote button and add 1, it is still 0. i just wonder if anyone can help with this.

import { useState } from 'react'

const App = () => {
  const anecdotes = [
    'If it hurts, do it more often',
    'Adding manpower to a late software project makes it later!',
    'The first 90 percent of the code accounts for the first 10 percent of the development time...The remaining 10 percent of the code accounts for the other 90 percent of the development time.',
    'Any fool can write code that a computer can understand. Good programmers write code that humans can understand.',
    'Premature optimization is the root of all evil.',
    'Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.',
    'Programming without an extremely heavy use of console.log is same as if a doctor would refuse to use x-rays or blood tests when diagnosing patients'
  ]
   
  const [selected, setSelected] = useState(0) 
  const scores = { 0: 0, 1: 0, 2: 0, 3: 0, 4:0, 5:0, 6:0 }
  const [point, setPoint] = useState(scores)
  
  return (
    console.log (selected),
    console.log (scores[selected]),
    <div>
      {anecdotes[selected]}
      <br></br>
      <button onClick ={()=> setPoint (point[selected] +1 )}>Vote</button>
      <button onClick={()=> setSelected(Math.floor(Math.random()* anecdotes.length ))}>next anecdotes</button>
      {scores[selected]}

    </div>
  )
}
/*onst Set = (...[points, selected]) => {
  points [selected] += 1;
  console.log(points [selected]);
<h1>{points}</h1>
}*/

export default App

Error: ENOENT: no such file or directory – at Object.unlinkSync

I have a script

if (fileName.includes(file)) {
       console.log('file deleted successfully: ', fileName)
       fs.unlinkSync(fileName)
   }

But at random times (flaky behaviour), getting this error

Error: ENOENT: no such file or directory, unlink '/harness/cypress/screenshots/file1 (failed).png' at Object.unlinkSync

This is inside a cypress command
on('after:spec', (spec, results) => {}

I tried asserting (if fileName && file && fileName.includes(file)), then perform deletion, still the same issue arises.

How can I add a (CSS) cursor: property to elements in an array?

I am trying to style the data array, so that when you hover over it the cursor is set to cursor: grab;. I tried using different elements to make it happen none worked ,
.li{}, .ol{}, MediaComponent{},img{},imgSrc{},data{},div{}. The only one that worked for me was *.{}, however the problem with this is that the cursor remains on the grab property for the rest of the elements on the page. I’m trying to code it so that the cursor:grab; element only pertains to the data array.

import React, { Component,useRef, setStatus, status } from 'react';
import './Turkish.css';

import turk1 from "./music/turk1.mp3";
import turk2 from "./music/turk2.mp3"
import turk3 from "./music/turk3.mp3"
import turk4 from "./music/turk4.mp3"

const data = [
    { imgSrc: 'turk1.png', audioSrc: turk1 },
    { imgSrc: 'turk2.png', audioSrc: turk3 },
    { imgSrc: 'turk3.png', audioSrc: turk4 },
    { imgSrc: 'turk4.png', audioSrc: turk2 },
  ];
  
  export default class Turkish extends Component {
    render() {
      return (
        <div>
          <ol>
            {data.map(({ imgSrc, audioSrc }) => (
              <MediaComponent imgSrc={imgSrc} audioSrc={audioSrc} />
            ))}
          </ol>
        </div>
      );
    }
  }
  
  const MediaComponent = ({ imgSrc, audioSrc }) => {
    const audioRef = useRef(null);
    const toggleAudio = () =>
      audioRef.current === null
        ? console.log("Audio component is not loaded yet.")
        : audioRef.current.paused
        ? audioRef.current.play()
        : audioRef.current.pause();

        
            return (
              <li>
                <img src={imgSrc} onClick={toggleAudio} />
                <audio
                  ref={audioRef}
                  src={audioSrc}
                  onLoad={() => setStatus({ ...status, isLoaded: true })}
                  onPlay={() => setStatus({ ...status, isPlaying: true })}
                  onPause={() => setStatus({ ...status, isPlaying: false })}
                  onError={() => setStatus({ ...status, error: true })}
                />
              </li>
            );
          };

Any thoughts?

Thank You

-Zpo

Determine Contrast of RGB Pixel

I’ve come across this very useful question about determining the perceived brightness of an RGB color and I was wondering if there was something similar on determining the contrast an RGB color.

Formula to determine perceived brightness of RGB color

Perceived Luminance

const inverseGamma = (sC) => {
  const c = sC / 255;
  if (c <= 0.04045) return c / 12.92;
  return ((c + 0.055) / (1.055)) ** 2.4;
};

const gamma = (c) => {
  let gammaColor = c;
  if (c <= 0.0031308) gammaColor *= 12.92;
  else gammaColor = 1.055 * gammaColor ** (1 / 2.4) - 0.055;

  return gammaColor * 255;
};

const ConvertToRGB = (image) => {
  const canvas = document.createElement('canvas');
  const ctx = canvas.getContext('2d');
  ctx.drawImage(image, 0, 0, 1280, 720);
  const rgbaData = ctx.getImageData(0, 0, 1280, 720).data;

  const mappedRGBdata = chunk(rgbaData, 4);

  const perceivedLuminanceArray = mappedRGBdata.map((rgb) => {
    const pixelRGB = rgb;
    return gamma(
      RY * inverseGamma(pixelRGB[0])
      + GY * inverseGamma(pixelRGB[1])
      + BY * inverseGamma(pixelRGB[2]),
    );
  });

  return perceivedLuminanceArray;
}

String without repeated characters

Thanks for helping
I have r = to how many times can letter be repeated in a row and s = to string to check.
For example if s = “aaabbbccc777” and r = 2. result = “aabbcc77”.
I need it to be dynamic.

Thanks for the help in advance.

let s = "bbbaaaccc777cdggg";
let r = 2;

const verification = (s, r) => {
    
}
verification(s, r);

Using v-carousel with a static image

I am trying to use Vuetify’s v-carousel but with a static image and only utilize the carousel for transitioning texts. So I have the carousel and the same image is being used across each carousel item but the issue is to keep the “sliding” effect it also slides the image. This is not an issue if the image was just a base color but since it is an image it makes it look odd. I only want the text to move.

My Initial Code:

<template>
  <v-carousel
    cycle
    height="400"
    hide-delimiter-background
    show-arrows-on-hover
  >
    <v-carousel-item
      v-for="(slide, i) in slides"
      :key="i"
      :src="/path/to/img.png"
    >
      <v-row
        class="fill-height"
        align="center"
        justify="center"
      >
        <div class="text-h2">
          Slide {{ i + 1 }}
        </div>
      </v-row>
    </v-carousel-item>
  </v-carousel>
</template>

I have tried appending a v-img into the code so it look like:

<template>
  <v-carousel
    cycle
    height="400"
    hide-delimiter-background
    show-arrows-on-hover
  >
    <v-carousel-item
      v-for="(slide, i) in slides"
      :key="i"
    >
      <v-img src="/path/to/img.png" />
      <v-row
        class="fill-height"
        align="center"
        justify="center"
      >
        <div class="text-h2">
          Slide {{ i + 1 }}
        </div>
      </v-row>
    </v-carousel-item>
  </v-carousel>
</template>

I have also tried making the image a v-sheet and putting the text on top but it still gives off the sliding effect. Is this possible to do or should I be going down a different route?

Need to improve JS function using a few || (logical or) or mayby another solution

I have function it works good but I want to improve that

  const canPrepareReview = (): boolean => {
if (loading) return true;
if (Object.keys(assets).length !== 0) return true;
return master;

}

  <Button
    disabled={!canPrepareReview()}
  >

I try to use something like this

  <Button
    disabled={loading || master || Object.keys(assetsSelected).length === 0}
  >     

but it does not work So any ideas on how it can be improved?

How to adjust the position of the ball in a ruler chart between measurements -100, 0, 100 inside the canvas?

There’s a graph that has measurements ranging from -100 to 0 and 0 to 100. What I need to do is adjust the calculation of the ball’s position with the number according to the gradientDataChart input, which can be a value between -100 and 100, the problem is proportionality, depending on the screen, the ball is disappearing, I was using distance 16, but it only worked for a width of 586px;

I tested it here if that might make it easier.

Just writing this code, I used 38 for 900 width, the problem is that if you change it to 1000, it goes out of position… it needs to be responsive:

var widthDefault = 900, metric = -100, calcPos = 38 * ((metric / widthDefault) * 100);
      ctx.beginPath();
      canvas.width = widthDefault;
      ctx.translate(calcPos, 0);
      var centerX = canvas.width / 2; 
      var centerY = canvas.height / 2;
      ctx.arc(centerX, centerY, 24, 0, Math.PI * 2, false);
      ctx.fillStyle ="#ffffff";
      ctx.fill()
      ctx.font = 'bold 14pt sans-serif';
      ctx.textAlign = 'center';
      ctx.strokeStyle ='#622BCF'
      ctx.stroke();
      ctx.fillStyle ="#622bcf80"; 
      ctx.fillText(`${medida}`, centerX, centerY+8);
      ctx.globalCompositeOperation = 'destination-over';

Image example:
enter image description here

Flexbox scroll overflowing content in an dynamic sized parent

I have a simple menu and content div structure. The menu has no fixed size and can expand depending on its content. The content div underneath should take the available space and scroll its own content if overflowing. Unfortunately, flexbox now behaves in such a way that the content div, due to its flex:1 property, expands according to its content instead of scrolling the content.

Is there a way to preserve the dynamic sizes using flex:1 and also have the content of the content div scroll?

    function toggleMenu() {
      const menu = document.querySelector(".menu");
      if(menu.classList.contains("open")) {
        menu.querySelector(".text").innerHTML = "<p> small text </p>";
        menu.classList.remove("open");
      }else {
        menu.querySelector(".text").innerHTML = "<h1> im the menu </h1>";
        menu.classList.add("open");
      }
    }
    body {
      padding: 0;
      margin: 0;
      background-color: #17141d;
      display: flex;
      height: 100vh;
    }

    .main {
      display: flex;
      flex-direction: column;
      flex: 1;
      background-color: grey;
    }

    .menu {
      background-color: blueviolet;
    }

    .content {
      display: flex;
      flex: 1;
      background-color: aqua;
    }

    .segment-wrapper {
      flex: 1;
      display: flex;
      background-color: red;
      flex-direction: column;
      overflow-y: scroll;
      padding: 10px;
      box-sizing: border-box;
    }

    .segment {
      height: 500px;
      background-color: green;
      border-radius: 5px;
      border: solid 1px black;
      width: 100%;
      margin-bottom: 10px;
    }
  <div class="main">
    <div class="menu open">
      <div class="text"><h1>im the menu</h1></div>
      <button onclick="toggleMenu()">Toggle</button>
    </div>
    <div class="content">
      <div class="segment-wrapper">
        <div class="segment">

        </div>
        <div class="segment">

        </div>
        <div class="segment">

        </div>
      </div>
    </div>
  </div>

localstorage setitem() is not working in some cases

I’m using react reducer to handle a request for a deleting an item from the list:

case 'REMOVE_ITEM': {
      let products = state.products!
      for( var i = 0; i < products.length; i++){ 
    
        if ( products[i].id === action.payload) { 
          products.splice(i, 1); 
        }
      }

      let result = {...state, products: products, productSelected: products[0]}
      localStorage.setItem('state', JSON.stringify(result))
      console.log(result)
      return { ...state, products: products, productSelected: products[0]}
    }

When I click the first item everything works great, but when I delete other items, my state updating and console.log(result) work fine, but there are no updates to localstorage, so I assume that setItem is not launching.
I would greatly appreciate if someone could help me with this issue.

Set focus to input element within find method

Given a form with error states, when the user hits a submit button, the focus should move to the first field with an error state. I’m able to grab the first instance of a field with an error state using:

[...document.querySelectorAll(".form-w1")].find(el => el.classList.contains("error"))

but can’t get the input field nested in the div to set focus to it.

console.log([...document.querySelectorAll(".form-w1")].find(el => el.classList.contains("error")))
<span class="form-w1">
  <label>
    <span>First Name</span>
  </label>
  <span>
    <input id="f1" type="text" required="" placeholder=" ">
    </span>
</span>
<span class="form-w1 error">
  <label>
    <span>Last Name</span>
  </label>
  <span>
    <input id="f2" type="text" required="" placeholder=" ">
    </span>
</span>