AG Grid dynamic picture based on parsed data not used in another column?

I’m just learning AG Grid for the first time and if I understand correctly initialization of the table is parsing my data to populate the rows given the columns I’ve given. I would like to access a part of the current data being parsed to pass it to a custom image component to be used in the table. I’m not sure how to access this data or if it’s even possible. Any insight would be appreciated.

Current code:

export default function Table() {

    const [tableData, setTableData] = useState([])

    const fetchData = async() => {
        await fetch('https://api.fantasycalc.com/values/current?isDynasty=false&numQbs=1&numTeams=12&ppr=1')
        .then(res => res.json())
        .then(data => setTableData(data))
        .catch(err => console.log(err))
    }

    const CustomImageComponent = (id) => {
        var imgLink = 'https://a.espncdn.com/combiner/i?img=/i/headshots/nfl/players/full/'+{id}+'.png'
        return <a href={imgLink}>player image</a>
    }

    const [colDefs, setColDefs] = useState([
        { field: "overallRank" },
        { field: "player.name" },
        { field: "picture", 
            cellRenderer: CustomImageComponent(***need to pass id here***),
        }
      ]);

    //always runs first
    useEffect( () => {
        fetchData()
    },[]
    )

    return (
        // wrapping container with theme & size
        <div
         className="ag-theme-quartz" // applying the Data Grid theme
         style={{ height: 500 }} // the Data Grid will fill the size of the parent container
        >
          <AgGridReact
              rowData={tableData}
              columnDefs={colDefs}
          />
        </div>
       )
}

Example JSON object contained in tableData: (I need to access the player.espnId field)

{
"player": {
"id": 5494,
"name": "Christian McCaffrey",
"mflId": "13130",
"sleeperId": "4034",
"position": "RB",
"maybeBirthday": "1996-06-07",
"maybeHeight": "71",
"maybeWeight": 210,
"maybeCollege": "Stanford",
"maybeTeam": "SF",
"maybeAge": 28.2,
"maybeYoe": 7,
"espnId": "3117251",
"fleaflickerId": "12892"
},
"value": 10243,
"overallRank": 1,
"positionRank": 1,
}

I’ve tried using ValueGetter to supply the cellRenderer params but couldn’t get it to work. I think this is because ValueGetter is only for fields actually being used in the table, whereas I’m trying to access an ID not stored in the table.

Digital Root Function returns “undefined”

I’m new to programming!

Trying to write a function that obtains the digital root of a number.

Currently struggling with the “for loop” and “if else” portion of the formula that returns “undefined”. Can you please give me any feedback and explain where my errors are specifically?

function digitalRoot(n) {
  let sum = 0;// define variable for loop calculations
  let str = n.toString(10,'')// convert number into string
  if (str.length === 1) { // test if string length is more than 1 character
    return str * 1; // if 1 character, return that string value and convert it back to a number
    }
  else {
    return 
    let strArray = parseInt(str.split(','))// if more than 1 character, split string into individual characters & convert back to numbers
    for (let i = 0; i < strArray.length; i++) { // sum up the numbers and repeat until there is just a single digit result
      sum += strArray[i];
    }  
  }
}

Having trouble with stripe as it keeps making a new subscription for the user after every refresh

import Stripe from 'stripe';
import { NextResponse, NextRequest } from "next/server";

const stripeSecretKey = process.env.STRIPE_SECRET_KEY as string; 

const stripe = new Stripe(stripeSecretKey, {
     apiVersion: '2024-06-20',
});


export async function POST(req: NextRequest) {

  try {
    const data = await req.json();
    const { priceId, userId, email } = data;

    if (!userId) {
      throw new Error("User ID is not provided");
    }

    const customer = await stripe.customers.create({
      metadata: {
        userId: userId,
      },
      email: email
    });


    const subscription = await stripe.subscriptions.create({
      customer: customer.id,
      items: [{ price: priceId }], 
      payment_behavior: 'default_incomplete',
      collection_method: 'charge_automatically', 
      expand: ['latest_invoice.payment_intent'],
      payment_settings:{
        payment_method_types: ['card']
      }
    });

    const latestInvoice = subscription.latest_invoice;
    if (!latestInvoice || typeof latestInvoice === 'string') {
      throw new Error('Latest invoice is not available or is of unexpected type');
    }

    const paymentIntent = latestInvoice.payment_intent;
    if (!paymentIntent || typeof paymentIntent === 'string') {
      throw new Error('Payment intent is not available or is of unexpected type');
    }

    return NextResponse.json({ clientSecret: paymentIntent.client_secret }, { status: 200 });

  } catch (error) {
    console.error('Error creating subscription:', error);
    return NextResponse.json({ error: error }, { status: 400 });
  }
}
rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /customers/{uid} {
      allow read, write: if request.auth != null && request.auth.uid == uid;

      match /checkout_sessions/{id} {
        allow read, write: if request.auth != null && request.auth.uid == uid;
      }
      match /subscriptions/{id} {
        allow read: if request.auth != null && request.auth.uid == uid;
      }
      match /payments/{id} {
        allow read: if request.auth != null && request.auth.uid == uid;
      }
    }

    match /products/{id} {
      allow read: if true;

      match /prices/{id} {
        allow read: if true;
      }

      match /tax_rates/{id} {
        allow read: if true;
      }
    }
  }
}
   
    const userRef = doc(db, "customers", userId);
    const userDoc = await getDoc(userRef);

    if (userDoc.exists()) {
      const userData = userDoc.data();
      if (userData.subscriptionId) {
       
        const subscriptionId = userData.subscriptionId;
        const subscription = await stripe.subscriptions.retrieve(subscriptionId, {
          expand: ['latest_invoice.payment_intent'],
        });

        if (subscription.latest_invoice && typeof subscription.latest_invoice !== 'string') {
          const paymentIntent = subscription.latest_invoice.payment_intent;

          if (paymentIntent && typeof paymentIntent !== 'string') {
            return NextResponse.json({ clientSecret: paymentIntent.client_secret }, { status: 200 });
          }
        }

        throw new Error('Payment intent not found or invalid');
      }
    }


Error creating subscription: [FirebaseError: Missing or insufficient permissions.] {
  code: 'permission-denied',
  customData: undefined,
  toString: [Function (anonymous)]
}
 POST /api/subscribe 400 in 147ms
Error creating subscription: [FirebaseError: Missing or insufficient permissions.] {
  code: 'permission-denied',
  customData: undefined,
  toString: [Function (anonymous)]
}
 POST /api/subscribe 400 in 147ms
[2024-08-11T21:41:23.341Z]  @firebase/firestore: Firestore (10.12.3): GrpcConnection RPC 'Listen' stream 0x3b35bbba error. Code: 1 Message: 1 CANCELLED: Disconnecting idle stream. Timed out waiting for new targets.
 GET /signUp 200 in 38ms
Error creating subscription: [FirebaseError: Missing or insufficient permissions.] {
  code: 'permission-denied',
  customData: undefined,
  toString: [Function (anonymous)]
}
 POST /api/subscribe 400 in 260ms
Error creating subscription: [FirebaseError: Missing or insufficient permissions.] {
  code: 'permission-denied',
  customData: undefined,
  toString: [Function (anonymous)]
}
 POST /api/subscribe 400 in 260ms
[2024-08-11T23:05:36.893Z]  @firebase/firestore: Firestore (10.12.3): GrpcConnection RPC 'Listen' stream 0x3b35bbbb error. Code: 1 Message: 1 CANCELLED: Disconnecting idle stream. Timed out waiting for new targets.

So Im trying to set up stripe payment for my project that I’m also using firebase to manage my auth. Im having trouble every time I load my /signUp page it will attempt to create two separate subscriptions, or if i refresh the page it will do the same thing i want it to create one subscription per user and then update that subscription. How would I do this.

I’ve adding the check above but getting a permission error

the first code is my subscribe api that is working but will create multiple subscription for a user including when refreshing the page

the second is my rules that i have in firestore

the third code was my attempt to include a check to see if a subscription attempt has been made on the user currently logged in

and the last bit is the error i was getting following

sorry this is my first time using stack so bare with me please

How can I reduce multiple lines in just only one

I have a query that returns data in this structure: name | age | idMessage.

So, I have results like that:

John | 34 | 1
John | 34 | 2
John | 34 | 3

So the query returns multiple lines but I need to deal with it to show just one line in my frontend with all idMessages separated by comma.

How can I agregate this data in just one line but with all idMessage values like that:
John | 34 | 1, 2, 3

I tried use filter but it not seems the best way to deal with it.

What’s Mean Immutability in javascript

So In Javascript Docs They Said The All Primitives Are Immutable

so my question is
when i write let x = 'foo';
x = 'bar';
is this mean that a foo Is In a spererate memory location
and bar in another memory location and the garbage collection will collect the old one which is foo

or is it just replacing the value of foo to bar in the same memory location which is firstly defined ?

Why would my PERN web applicaton deployed with Render only have the Server running and not the Client?

I’m running into an issue while trying to deploy my PERN application. The database is already set up and linked. The deployment process is not failing, but when you follow the link to the site it only is showing the json responses to the servers routes.

These are the scripts that I am using in my applications main package.json:

"scripts": {
"test": "echo "Error: no test specified" && exit 1",
"build": "cd frontend && npm install && npm run build && cd ../backend && npm install",
"start": "node backend/server.js"
},

The build and start commands are what are used in the deployment. Here is how I am trying to connect my backend to the dist directory’s index.html file in backend/server.js:

”’

"use strict";

/** Server start up logic */
// Imports
const express = require('express');
const app = require("./app");
const { PORT } = require("./config");
const path = require('path');

app.use(express.static(path.join( __dirname, '..', 'frontend', 'dist')));

app.get('*', (req, res) => {
   res.sendFile(path.join( __dirname, '..', 'frontend', 'dist', 'index.html'));
});

app.listen(PORT, function() {
   console.log(`Started on Port:${PORT}`);
})

Since I am a novice, I don’t know what else may be useful to solve this problem. So please let me know where other trouble areas may be.

Why does input.onChange() in my form triggers AsyncValidation Error?

This is my search.jsx Component

const Search = ({
    input,
    isFetching,
    isSelected,
    message,
    options,
    handleSearch,
    handleChange,
    handleSave,
    handleCancel,
}) => (
    <Container>
        <StyledDropdown
            fluid
            selection
            placeholder="Search Name/Email"
            onChange={handleChange}
            onSearchChange={handleSearch}
            options={options}
            search={options => options}
            loading={isFetching}
            noResultsMessage={message}
            selectOnNavigation={false}
        />
        <Buttons>
            <Button type="button" content="Save" primary onClick={handleSave} disabled={!isSelected} />
            <Button type="button" content="Cancel" onClick={handleCancel} />
        </Buttons>
    </Container>
);```

This is my search container, The form throws an error[![enter image description here](https://i.sstatic.net/Z1HkAOmS.png)](https://i.sstatic.net/Z1HkAOmS.png)everytime I click Save and the HandleSave Function is triggered.

This is the handleSave method in the search.jsx container. The form Works fine if I remove the input.onChange() (but author_id is not added to the request payload since I removed that part, Obviously!)


handleSave = () => {
this.props.input.onChange(this.state.value); //-> throws function passed to reduxForm must return a promise
this.props.setSelected(this.getSelectedData());
this.props.toggleEditMode();
}“`

this is the parent container (author_selector.jsx) where search.jsx is called. Even here the input.onChange throws the same error!

class AuthorSelectorContainer extends Component {

    static propTypes = {
        isEditing: bool.isRequired,
        fetchAuthor: func.isRequired,
        setSelected: func.isRequired,
        ...
    };

    componentDidMount() {
        const {
            meta, input, fetchAuthor, setSelected, defaultUserData,
        } = this.props;

        if (meta.initial) {
            fetchAuthor(meta.initial);
        } else {
            setSelected(defaultUserData);
            //input.onChange(defaultUserData.id);  //-> throws function passed to reduxForm must return a promise
             
        }
    }

    render() {
        const { meta: { initial }, selected, isEditing } = this.props;
        const readOnly = (initial !== undefined);

        if (isEditing) {
            return <Search {...this.props} />;
        } else if (selected) {
            return <AuthorSelectorForm {...this.props} readOnly={readOnly} />;
        }
        return null;
    }
}


const mapStateToProps = state => ({
    selected: getSelected(state),
    isEditing: isEditing(state),
    defaultUserData: getUserData(state),
});

This is my middleware.js ( I can’t see why validation is triggered)

const apiMiddleware = store => next => async (action) => {
    const { type, payload } = action;
    const { getState, dispatch } = store;



    if (!type.startsWith('API/')) {
        return next(action);
    }

    const state = getState();
    const access_token = getToken(state);

    if (access_token && payload.url !== '/oauth/token') {
        payload.params = { access_token, ...payload.params };
    }

    const config = {
        baseURL: getBaseURL(state),
        ...payload,
    };

    // pass action to next middlewear. mostly for showing the dispatch on devTool
    next(action);

    try {
        const res = await axios(config);
        return res;

    } catch (error) {
        if (error.response) {
            if (error.response.status === 401) {
                // Unauthorized
                logout()(dispatch);
                dispatch(ui.flash.warn({ header: 'Login Expired', content: 'Please login again' }));
            }
        } else if (error.request) {
            dispatch(ui.flash.error({ header: 'Network Failure', content: 'API server not available' }));
        } else {
            // Something happened in setting up the request that triggered an Error
            dispatch(ui.flash.error({ header: 'Error', content: error.message }));
        }

        throw error;
    }
};

I have tried directly updating state without invoking reduxForm (which has some other issues!).

I have also tried bypassing validation which doesn’t work.

const AuthorSelectorForm = reduxForm({
    form: 'authorSelectorForm',
    validate: undefined,
    asyncValidate: undefined,
})(AuthorSelector);

I want to understand how input.onChange() can trigger async Validation error. How should I got about debugging this issue. Thank you for taking a look!

How can I trigger re-render of an element (which uses state) in a callback function?

I am currently using React (TSX) and have run into a problem regarding states. I am fairly new to this topic so I apologize if this is blatantly obvious to fix..

Consider a callback function testComponent, which, when a button is pressed, renders a new component each time.

Within this component, there will be a select tag and an input tag, and based on what is selected, the input tag must also update.

The select tag will display the name of the object, and the input tag will display its ID, for example.

And, all of the selectedOptions will start off with a default value of options[0] which happens in a useEffect.

This is a recreation of my problem just using the word test instead so that its easier to understand (less context needed). The idea is that every time the select element changes, it should also update the input tag.

export default function CreateTestComponent() {
  const options: any[] = [
    {
      id: 1,
      name: "Test 1"
    },
    {
      id: 2,
      name: "Test 2",
    },
    {
      id: 3,
      name: "Test 3"
    }
  ]
  const [selectedOptions, setSelectedOptions] = useState<any[]>([options[0]]);
  const [testComponentIndex, setTestComponentIndex] = useState<number>(0);
  const [components, setComponents] = useState<any[]>([]);

  useEffect(() => {
    setComponents([testComponent(0)]);
    setTestComponentIndex((old) => old + 1);

    for (let i = 0; i < options.length; i++) {
      setSelectedOptions((old) => {
        const temp = [...old];
        temp[i] = options[0];
        return temp
      })
    }
  }, [])


  const testComponent = (index: number) => {

    return (
      <div className="flex flex-row gap-5" id={`${index}`}>
        <select
          onChange={((e) => {
            const id = e.target.value;
            setSelectedOptions((old) => {
              const temp = [...old]
              temp[index] = options.filter((option) => option.id == id)[0];
              return temp;
            })
          })}>
          {options.map((option, index: number) => {
            return (
              <option key={index} value={option.id}>
                {option.name}
              </option>
            );
          })}
        </select>
        <input readOnly value={selectedOptions[index].id} />
      </div>
    )
  }

  return (
    <>
      <button type="button" onClick={() => {
        setTestComponentIndex((old) => old + 1)
        setComponents([...components, testComponent(testComponentIndex)]);
      }} className="bg-black text-white rounded px-3 py-1">
        Add a Component
      </button>
      <div>
        <h1>Component testing!</h1>
        <div>
          <ul className="list-none">
            {components.map((component: any, index: number) => {
              return (
                <li key={index}>
                  <div className="flex flex-row gap-5">
                    {component}
                  </div>
                </li>
              )
            })}
          </ul>
        </div>
      </div>
    </>
  )
}

This code will work in a .tsx file.

As you can see, the state is updating, but the input tag doesn’t update. I have done an annoying amount of research trying to figure out what is happening, and I am pretty sure that because it is inside a callback function in which the state is not continuously updated (which would, in turn, trigger a rerender).

I tried doing a bunch of things to get around this obstacle. Namely, I tried useRef(), but it doesn’t have the capability of rerendering, which only useState appears to do.

I went through a bunch of other things but none of them got around this problem because none of them combatted the problem that is that the state is not the same outside versus inside the callback function.

If there is no way around having an up-to-date state within a callback function, what are some other alternatives I could try so that I could still have the ability of pressing a button and generating a new instance of a component each time?

Thanks

Infinite Scrolling PAGE AND LIMIT

Asking about the _page=${page}&_limit=${PAGE_SIZE + 1} when trying to use my own API or JSON FILE

  const fetch = async () => {
    axios
      .get(
        `https://jsonplaceholder.typicode.com/posts?_page=${page}&_limit=${
          PAGE_SIZE + 1
        }`
      )
      .then((response) => {
        const data = response.data;
        const items = response.data.slice(0, 8);

        setHasMore(data.length > PAGE_SIZE);
        if (posts.length === 0) {
          setPosts(items);
        } else {
          setPosts((v) => [...v, ...items]);
        }
      })
      .finally(() => {
        if (!bootstrapped) {
          setBootstrapped(true);
        }
      });
  };`

App content vertically centered, BUT WHY?

I’m working on a React application where I have a fixed header at the top of the page. Below the header, I have a content area that should start immediately after the header. However, the content appears to be vertically centered within the viewport, and I’m not sure why.

When resizing the browser window the content is displayed from the top, as it should.

So it kinda works but also not?

This is my relevant .js and .css:

.js:

import React, { useState, useEffect, useRef } from 'react';
import { Link } from 'react-router-dom';

const BrowseAll = () => {
    const [posts, setPosts] = useState([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);
    const scrollContainerRef = useRef(null);

    useEffect(() => {
        fetchAllPosts();
    }, []);

    useEffect(() => {
        const updateBodyHeight = () => {
            if (scrollContainerRef.current) {
                scrollContainerRef.current.style.height = `${window.innerHeight}px`;
            }
        };

        window.addEventListener('resize', updateBodyHeight);
        updateBodyHeight();

        return () => {
            window.removeEventListener('resize', updateBodyHeight);
        };
    }, []);

<----- some more code here inbetween ----->

    return (
        <div className="browse-all" ref={scrollContainerRef}>
            <h1>All Posts</h1>
            {posts.map(post => (
                <div key={post._id} className="post bg-gray-800 text-white rounded-lg p-4 mb-4 w-full max-w-2xl">
                    <h2 className="text-2xl font-semibold">{post.title}</h2>
                    <p className="mb-2">{post.content}</p>
                    <p className="mb-2">Posted on: {new Date(post.created_at).toLocaleString()}</p>
                    <Link to={`/post/${post._id}`} className="mt-4 inline-block text-center bg-blue-500 text-white py-2 px-4 rounded">
                        View Post Details
                    </Link>
                </div>
            ))}
        </div>
    );
};

.css:

.browse-all {
    min-height: 100vh;
    margin-top: 60px;
    padding: 20px;
    max-width: 800px;
    margin: 0 auto;
}

.browse-all body {
    overflow: auto;
}

.browse-all h1 {
    text-align: center;
    margin-bottom: 20px;
}

.browse-all .post {
    background-color: #2a2a2a;
    border: 1px solid #3a3a3a;
    border-radius: 8px;
    margin-bottom: 20px;
    padding: 20px;
    align-items: left;
    text-align: left;
}

.browse-all .post h2 {
    margin-top: 0;
}

.browse-all .comments {
    margin-top: 10px;
}

.browse-all .comment {
    background-color: #3a3a3a;
    border-radius: 5px;
    padding: 10px;
    margin-top: 10px;
}

I tried removing the scrollContainerRef, the useEffect hook that sets the height and playing around with the CSS. No luck.

how to render a specific piece of data from Mysql database to my front end html using Js and node

so i am building a note system and how i have it setup is that on the home page it gives you a preview of the note and if you want to see the whole note you click on it and it pulls up a modal pop-up and would display the full note. im having trouble building my fetch request to get the specified note and then render it into the modal. any suggestions would very appreciated

iv tried just building a basic fetch request but i can only really find examples of POST requests or generic GETs that would just all my notes, not a specific one.

<div id="noteDisplay" class="noteDisplay">
<ul>
    <% note.forEach(note =>{ %>

    
    <li>
        <p><%= note.title%></p>
    </li>
    <li>
        <p><%= note.body.substring(0, 250)  %> <span class="noteViewModalBtn" id=<%= note.NoteId %>>...</span></p>
    </li>
    <% }) %>
</ul>

×

<div class="noteViewModalContent">

    
</div> 
    document.querySelectorAll('.noteViewModalBtn').forEach(item => {
item.addEventListener('click', event => {
//handle click
    fetch("http://localhost:8080/note")
    .then()
noteViewModal.style.display = "flex";
})

})

app.get("/note", checkNotAuthenticated, async(req, res) =>{  

const note = await getNote(id)
res.send(note)

})

 async function getNote(id){
const [rows] = await pool.query(`
    SELECT *
    FROM userNotes
    Where NoteId = ?
    `, [id])
    return rows

}

Very odd useEffect react nextjs issue

I have an odd issue I am dealing with. I have this useEffect function which is supposed to run on my program’s start to check that they are logged in, and generate a dynamic element, named lists. Code is below:

// Initial Effect: Fetch access and lists data on component mount
useEffect(() => {
    console.log('Running on launch!')
    getAccess();
    getLists();
}, []);

I am expecting this to run getLists() everytime the page is loaded. This is because our users can interact with the lists — they can add items to it and delete items (which updates our Postgres backend). I always want to dynamically pull the latest version of lists.

The function and route are shown below.

// Fetch list data from the server
const getLists = async () => {
    const data = await fetch("/api/prospects/getLists/");
    const json_data = await data.json();
    console.log(json_data);
    setLists([...json_data]);
};
"use server";

import * as db from "../../../../lib/db"
import { NextRequest, NextResponse } from 'next/server';

export async function GET(req: NextRequest) {
    const list = await db.query(`
    SELECT id, name FROM "List"
    ORDER BY name ASC
    `, []);
    
    return NextResponse.json(list.rows);
}

However, let’s say I add an element to the list and then refresh my page. I can verify the useEffect function is being called as I see “Running on launch!” executed in my console. However, the console.log where we log the json_data will ALWAYS show the original state of the list table. If I start the program with 5 elements in list, and add a sixth, no matter how many times I refresh the page, it is showing me that my route is only returning the original 5 elements. Same issue with deletion. It never gets updated.

Importantly, I confirmed that my postgres table is indeed taking the changes in real time. So it isn’t an issue with adding or deletion.

How do I fix it so it dynamically always pulls the latest version of the List table on refresh?

It should also be important to note it works correctly in my development environment, but if I build it using npm run build on my local machine, or push it to github to my live version on vercel, then this issue happens.

dnd kit nested button does not register onClick

I have a button nested in a sortable list using dnd kit and core UI, however when I click on a button, the onClick function does not event get called.

const [pIndex, setPeopleIndex] = useState(0)

const handleClick = (peopleIndex) => {
  console.log(peopleIndex) //This is being all passed in as `0` by <ListItemComponent /> 
}


{
  data.people.map((element, peopleIndex) => (
    <div key={peopleIndex}>
      <AccordianHeaderComponent onClick={() => setPeopleIndex(peopleIndex)} />
      <DndContext
        sensors={sensors}
        collisionDetection={closestCenter}
        onDragEnd={handleDragEnd}
      >
         <SortableContext
           items={element.addresses}
           strategy={verticalListSortingStrategy}
         >
           {
             element.addresses.map((address, addressIndex) => (
                <ListItemComponent 
                  key={addressIndex} 
                  handleClick={handleClick}
                  peopleIndex={peopleIndex}
                />
             ))
           }
        </SortableContext>
     </DndContext>
   </div>
 ))
}
const ListItemComponent = ({handleClick, peopleIndex}) => {
    const {
    attributes,
    isDragging,
    listeners,
    setNodeRef,
    transform,
    transition,
  } = useSortable({ id: dragID });

  return (<li 
           onClick{openModal}
           id={dragID}
           ref={setNodeRef}
           style={style}
           {...attributes}
           {...listeners}
          >
           <MenuDropDown openModal={openModal} />
          </li>
        )
}
// MenuDropDown Component

const MenuDropDown  = ({openModal}) => {

  const handleMenuItemClick = () => openModal()

  return (
   <CDropDown>
     <CDropdownToggle className="bg-white border-none" caret={false}>
       <CIcon icon={cilOptions} size="lg" />
     </CDropdownToggle>
     <CDropdownMenu>
       <CDropdownItem onClick={handleMenuItemClick}>Edit Question</CDropdownItem>
     </CDropdownMenu>
   </CDropDown>
  )
}

For some reason, when clicking on MenuDropDown which should show a drop down menu, is not working after adding dnd kit to the list of items

How to remove ‘hidden’ class [closed]

I am having trouble removing the ‘hidden’ class on my inputPlaceholder. I checked the console, and the hidden class remains after clicking the “allClearBtn.”

Here is my code:

const resultBox = document.querySelector("#result");
const inputPlaceholder = document.querySelector('.result-span')
function clearInput() {
  inputPlaceholder.classList.remove('hidden',);
}
numberBtns.forEach(function (number){
  number.addEventListener("click", function(){
    inputPlaceholder.classList.add('hidden');
    resultBox.innerHTML += number.innerHTML;
  });
});

I tried using classList.replace(), using a visible class which set my inputPlaceholder to “display:block”, but that did not work. I also made sure my clearInput function was being triggered by doing resultBox.textContent = ”, which did work.

How to get selected text in JavaScript as a string while including alt text from images using document.getSelection()?

I’m trying to write a function that triggers when the user copies text, the function should add the selected text to the clipboard minus any blank lines. Consider the following HTML:

<html>
Blah blah
<br><br>
<img src="https://en.wikipedia.org/static/images/icons/wikipedia.png" alt="alt" />
<br><br>
blah blah
</html>

This gives the following result when copying the entire page:

Blah blah

alt

blah blah

Great, now I just need to intercept the copy event and remove the blank lines. Add the following script to the above example:

<script>
document.addEventListener('copy', (event) => {
    var selectedText = document.getSelection().toString();
    //Code to remove blank lines will go here
    event.clipboardData.setData('text/plain', selectedText);
    event.preventDefault();
});
</script>

But now when you copy the entire page you get the following result:

Blah blah



blah blah

It skips the alt text of the image for some reason, now it replaces it with another blank line. Why?

My first thought is that toString() is somehow removing it, which would be very problematic since I need that to manipulate the copied text, but if I don’t include toString() I get the same result.

Why is document.getSelection() giving me a different result than when I copy the page without it?