Using MDX and rehype-highlight on a next.js website to render an MD containing code causes Object.hasOwn crash

I have pretty standard setup that is closely based on the examples from next.js and next-mdx-remote. Everything works, until I add rehypeHighlight to the rehypePlugins array. Then I get this error, any idea why that would happen? Thanks.

TypeError: Object.hasOwn is not a function

import { serialize } from "next-mdx-remote/serialize";
import rehypeHighlight from "rehype-highlight"

export async function getPostData(id) {
    const fullPath = path.join(postsDirectory, `${id}.md`);
    const fileContents = fs.readFileSync(fullPath, 'utf8');

    // Use gray-matter to parse the post metadata section
    const {content, data} = matter(fileContents)

    const mdxSource = await serialize(content, {
        // Optionally pass remark/rehype plugins
        mdxOptions: {
            remarkPlugins: [],
            rehypePlugins: [rehypeHighlight],
        },
        scope: data,
    });

    // Combine the data with the id and contentHtml
    return {
        id,
        mdxSource,
        data
    }
}

Rendering:

export async function getStaticProps({ params }) {
    const postData = await getPostData(params.id);
    return {
        props: {
            source: postData.mdxSource,
            postData: postData.data,
        }
    }
}

export default function Post({ source, postData }) {
    return (
        <Layout>
            <Head>
                <title>{postData.title}</title>
            </Head>

            <article>
                <h1 className={utilStyles.headingXl}>{postData.title}</h1>
                <div className={utilStyles.lightText}>
                    <Date dateString={postData.date} />
                </div>
                <section>
                    <MDXRemote {...source} />
                </section>
            </article>
        </Layout>
    );
}

Mapping over an array of objects to update stay

As part of my learning process into creating hooks and reducer functions Im trying to build a small quiz based application. And my issue is as follows.

I have managed to get the data I want into my api call hook, this is passed in as a destructured object, and I can now get my data back from said hook. I then retention purposes and passing it down as a prop, want to save this to a new piece of state.

My problem is as follows:

The data I get back comes back in the form of an array of objects and as a result I cannot seem to update the state.

export default function App() {
  // Params State
  const [params, setParams] = useState();
  // Question state
  const [questions, setQuestions] = useState({});
  // Start Game State
  const [start, setStart] = useState(false);

  // destucture reducer hook here
  const { reducerState, actions } = useQuestionData();
  // destructure trivia hook here
  const { questionData, isLoading, error } = useTrivia(params);

  // set start handler
  function handleSetStart() {
    setParams(reducerState);

    setQuestions(questionData);

    setStart(!start);
  }

  // getting question DATA
  console.log(questionData);
  // Becomes undefined here // need to spread data into objects
  console.log(questions);
  return (
    <div>
      <Header />
      <Debug reducerState={reducerState} start={start} />
      {!start ? (
        <GetQuestionData
          actions={actions}
          setStart={setStart}
          start={start}
          handleSetStart={handleSetStart}
        />
      ) : (
        <Main params={params} questionData={questionData} />
      )}
    </div>
  );
}

On “getting question data” i get my array of objects but then when I want to update my state it always comes back as undefined. It just won’t update. I feel im supposed to use MAP here but I can’t find a specific use case similar enough to what id like to do, so any pointers would be appreciated.


What I tried:

I tried looping over the array of objects to individually add them to the state, I have tried adding them to a new piece of state that has an array as it’s base and i’ve tried mapping the array, which I thought would be correct but seems not to be the case

Add onclick to SVG That is Referenced Using

I am attempting to add a dropdown for mobile that gets shown when you click on an SVG. The problem is the SVG is stored in a seperate file.
This is what I am doing to get the SVG into my document.

<object type="image/svg+xml" data="./media/svg/moon.svg" id="moon"></object>

When I realized that my onclick wasn’t working because the object tag only renders the seperate file, instead of taking its place, so I attempted to inject an onclick directly into the SVG tag. Then, when that didn’t work I realized the object tag doesn’t pass through javascript so I injected a script tag. When that didn’t work because it was still being rendered in another file and the document object wasnt being passed through I attempted to get the document file passed through. But nothing worked. I resolved to copy-pasting the SVG tag directly into the main file (instead of using ) and that worked. But I would like to continue to use different files as to ensure my index.html file remains uncluttered.
This is the final js I ended up with:

function svgInject(objectId, layerId, attr, val, post) {
    svg = document.getElementById(objectId).contentDocument.getElementById(layerId);
    svg.setAttribute(attr, val)
    script = document.createElement("script");
    script.setAttribute('src', '/js/script.js');
    script.setAttribute('type', 'text/javascript');
    svg.append(script);
    if (post === true) {
        console.log(this.document.getElementById('moonMenu').contentDocument.getElementById('moon'));
    };
};
function menuCheck() {
    // console.log(main.document)
    // console.log(document)
    toggle = document.getElementById('toggle1');
    console.log(toggle)

    if (toggle.checked === true){toggle.checked = false} else {toggle.checked = true};
};
svgInject('moonMenu', 'moon', 'onclick', 'menuCheck()');

Auth0 callback does not work on production

I have a React & Django application that works locally but not when deployed on Heroku.
Long story short, on local env after login it makes a request to /authorize and after redirect to /callback?code=xxx&state=yyy and server respond with 200 OK.

On prod, from the other hand, after calling /callback server gives 302 with Location to main page – “/”. No matter what page I will access, every time it gives 302 and falls into infinite loop.

There are absolutely no difference between local and prod. Also, all necessary URLs are set up in env paths and Auth0 dashboard.

This is my code for

callback/index.tsx

import { PageLoader } from "../../components/page-loader";
import { useEffect } from 'react';
import { useAuth0 } from '@auth0/auth0-react';


export default function Callback() {
    const { isAuthenticated, isLoading, error, loginWithRedirect } = useAuth0();

  useEffect(() => {
    if (!isLoading && !isAuthenticated) {
      console.log("User is not authenticated. Redirecting to login...");
      loginWithRedirect();
    }
  }, [isLoading, isAuthenticated, loginWithRedirect]);

  if (isLoading) {
    return (
      <div className="page-layout">
        <PageLoader />
      </div>
    );
  }

  if (error) {
    return <div>Error: {error.message}</div>;
  }

  return (
    <div className="page-layout">
      <PageLoader />
    </div>
  );
}

I added it to App.js

<Route path="/callback" element={<Callback />} />

providers/auth.tsx

import { AppState, Auth0Provider } from "@auth0/auth0-react";
import { useNavigate } from "react-router-dom";

const domain = process.env.REACT_APP_AUTH0_DOMAIN;
const clientId = process.env.REACT_APP_AUTH0_CLIENT_ID;
const audience = process.env.REACT_APP_AUTH0_AUDIENCE;
const redirect_uri = process.env.REACT_APP_AUTH0_CALLBACK_URL;

export default function AuthProvider({ children }: { children: React.ReactNode[] }) {
  const navigate = useNavigate();
  const onRedirectCallback = (appState?: AppState) => {
    navigate(appState?.returnTo || window.location.pathname);
  };

  if (!domain || !clientId || !audience || !redirect_uri) {
    throw new Error("One of the required environment variables is missing!");
  }

  return (
    <Auth0Provider
      domain={domain}
      clientId={clientId}
      onRedirectCallback={onRedirectCallback}
      authorizationParams={{
        audience: audience,
        scope: "profile email read:api",
        redirect_uri: redirect_uri,
      }}
    >
      {children}
    </Auth0Provider>
  );
}

and index.js

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <Router>
    <AuthProvider>
        <App />
    </AuthProvider>
  </Router>
);

Thank you

I tried changing callback URLs, compared local to prod environment and played with the Auth0 provider and settings.

App should return 200 OK after requesting /callback endpoint

Integrating Paged.JS into React/JS website

I’m attempting to display my html page with paged.js in a react project. The html loads fabulously from local host (not via npm start, but the live server ext on vscode), but when I tried to follow the steps on this website it just all messed up and not formatted in the paged.js way.

Also I’m using MUI library and I’m attempting to load it in a box (EDIT- MUI or not, the paged.js does not load with the proper format):

<Box sx={{ display: 'flex', flexDirection: 'row'}}>
   <Paper elevation={3}>
      <Box sx={{m:3}}>
         <Form/>
      </Box>
   </Paper>
   <Paper elevation={3}
      <Box sx={{m:3}}>
         <Report ...props/> //this is where I load my report
      </Box>
   </Paper>
</Box>

and my report function looks something like this:

function Report(props) {
     useEffect(() => {
        const paged = new Previewer();
        const DOMContent = document.querySelector('paged');
      
        paged.preview(DOMContent, ['/pagedjs.css'], document.body).then((flow) => {
          console.log('Rendered', flow.total, 'pages.');
        });
      }, []);
   
     return (
         <div className='paged'>
           whole bunch of report stuff
         </div>
     )
}

The form takes inputs that updates values in the report, so I’d like to see them side by side, but I don’t really care so much about that and will take any solution that gets paged.js to work in react at all.

If anyone has any idea it’ll be greatly appreciated. I’ve tried everything I could find on the internet already and nothing helped xD

I’ve also tried: jsPDF, react-pdf, and react-print, but the report is decently complex and has a lot of elements that so far I’ve only been able to achieve with paged.js

I want to apply fluid simulation effect on my website background but it should only be seen where the mouse hovers for certain area usinggsap or webgl [closed]

So problem is I am trying to someone webgl GitHub and it is coming on my website but I don’t kn how to put it on background and convert it to only hovering effect just like this website background effect https://preview.codecanyon.net/item/motion-art-for-elementor-wordpress-plugin/full_screen_preview/48826891?_ga=2.24447354.1106474036.1716321247-1399927600.1715928095

I tried using chatgpt but makes that even worse the effect is coming but as another container how to let it be in background with motion

jQuery prop method is rendering on next render cycle

The following code is working as far as setting the disabled attribute on the chosen element however it is not updating until the next render cycle so its behind one click/change of the checkbox.

    $(document).on('change', '#<%= checkSetSmtpCredentials.ClientID %>', function() {
        let isChecked = $(this).is(':checked');

        $('#<%= ddlSmtpAuthenticationMode.ClientID %>').prop('disabled', isChecked);
    });

jQuery is version 2.1.3 fwiw.

Current behavior:

  1. Checkbox has default state of unchecked, chosen element has default state of disabled="disabled"
  2. Click checkbox. Checkbox becomes checked
  3. chosen element stays disabled
  4. Click cb. Cb becomes unchecked
  5. Chosen element is now no longer disabled
  6. State is now opposite of what it should be

Chosen element is updated one render cycle behind the cb being changed.

Expected behavior:

When cb is checked, chosen element must be updated on that same render cycle.

Unable to fetch and update data due to infinite useEffect loop

i’m using React and Firestore so that users can fill out a form, submit it and find the data when they return.

Users are able to submit the form and i’m able to display the data but when updating the document is the problem.

export default function StudioName({ addData, vehicle, docReady }) {
  const [data, setData] = useState("");
  const [dataId, setDataId] = useState();

  useEffect(() => {
    if (docReady) {
      setData(vehicle.name);
    }
  }, [docReady, vehicle]);  //vehicle causes an infinite loop

  useEffect(() => {
    addData(dataId, data);
  }, [addData, dataId, data]);

  const onChange = (e) => {
    const { id, value } = e.target;

    setData(value);
    setDataId(id);
  };

  return (
    <>
      <div className="m-5" onChange={onChange}>
        <label className="">
          <span className="mr-2">Vehicle Name</span>
          <input
            className="border-b-2 border-t-0 border-l-0 border-r-0 focus:border-b focus:ring-0 focus:border-orange-400 border-orange-400"
            required
            type="text"
            id="name"
            value={data}
          />
        </label>
      </div>
    </>
  );
}

The first useEffect causes an infinite loop which prevents any update and if remove it, React will say that there’s a missing dependency.

Please advise.

gh-deploy app not working, but locally hosted does work

I’m building an Angular project that is the front end for an already function server side app that I created. I just deployed the Angular project with gh-pages, and it isn’t working correctly – but the app does work when I host it locally.

Not sure why this is? The gh-page that’s hosted, doesn’t allow me to login or signup, whereas the local one does. Also the picture background is different between the gh-page app and a local one. Server side, I already added the gh-page url to the allowedOrigins so it’s not that.

Please help?

Github: https://github.com/chrisspenceratx/myFlix-client-Angular
hosted gh-page: https://chrisspenceratx.github.io/myFlix-client-Angular/welcome/

My app isn’t working on a gh-page, but it does work when hosted locally.

window.location showing old value after redirect from authentication server

I am using keycloak as authentication server for my react app. The authentication flow is:

  1. App displays a login button. When clicked, url gets changed for that of keycloak with a redirect on /auth/callback
  2. /auth/callback uses the component Callback, that given the url search params finishes the authentication.

My problem is that keycloak returns a successful authentication and a redirect to callback, but in callback the url detected is still that of “/login”. This is the contents of my callback component

const Callback = () => {
    const { keycloakClient } = useKeycloak();
    const [authenticated, setAuthenticated] = useState<boolean>(false);

    useEffect(() => {
        console.info(window.location);
        const getTokens = async () => {
            await keycloakClient.authenticate();
            setAuthenticated(keycloakClient.authenticated());
        };
        getTokens();
    }, []);

    if (authenticated) {
        setHeadersInterceptor(keycloakClient);
        return <Navigate to="/todolists" replace />;
    } else {
        return <Navigate to="/login" replace />;
    }
};

and this component is only referenced in a route for /auth/callback. How is possible that when printing window.location, I am still getting /login instead of /auth/callback?

React Pong Game Ball Motion and Computer Paddle

I’m trying to make a pong game in React JS.
Making the player’s paddle move with the mouse events is relatively easy, but I’m a bit stuck on how to make the ball component move and collide with the paddles.

As for the computer’s paddle, I can move it up and down in a pattern but that is not how the computer’s paddle moves in the game. Seems to have some rudimentary “AI” to figure out where it should ideally go to hit the ball? I’m unsure about how to implement that as well, especially in cohesion with the ball’s movement.

I’d appreciate any guidance at all, thanks in advance!

window.open results in blank page after redirection

When I use window.open to open a site which redirects to my site, it results in only showing the background color of the body but without any visible content. The content loads but it’s not visible until I resize the page.

<button>Click</button>

document.querySelector('button').addEventListener('click', function() {
  window.open('https://dashboard.palatial.cloud/project/663cdb4789db9b22c12cff23/share', '_blank');
});

But this code using <a> works fine:

document.querySelector('button').addEventListener('click', function() {
  const a = document.createElement('a');
  a.href = 'https://dashboard.palatial.cloud/project/663cdb4789db9b22c12cff23/share';
  a.target = '_blank';
  a.click();
});

What is the difference between both approaches? I’m not able to change how the user is being directed to my site, so what would be a way to fix this on my side?

How to bundle a Create React App into a single embed.js file for embedding in any website?

I’m working on a React app using Vite and I want to create a single embed.js file that I can include in any website to load my widget. The embed.js file should contain both the JavaScript and CSS. I am using the vite-plugin-css-injected-by-js plugin to inject CSS via JavaScript.

What I have tried:

screenshot is attached,
see the dist directory of my repo

where i tried with this,

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import cssInjectedByJsPlugin from 'vite-plugin-css-injected-by-js';

export default defineConfig({
  plugins: [
    react(),
    cssInjectedByJsPlugin()
  ]
});

MOBILE – SAFARI : Preventing scroll reset to top on mobile when applying fixed position to body

I have a pop up on my website, it can go from hidden, to minimized, to fullscreen states, when on fullscreen, i obviously want to block the scroll of the page behind. So i add and remove the noscroll class when on fullscreen :

  .noscroll {
    height: 100%;
    overflow: 100vh; // fallback for browser not support svh
    overflow: 100svh;
  }

It works as sa charm on desktop but on mobile-safari, when the noscroll class is added, the body’s scroll position gets resetted to the top.

I’ve tried online the solutions including :

  • adding a position: fixed to the noscroll class -> not working in my case;
  • saving the scrollPosition to add it again once the popup is removed -> like on twitter or instagram, when we reach the top of the page, the app searches for new content, this is triggered everytime i open the popup, i need to avoid that and resetting the scroll position after it happened doesn’t solves my problem

Isn’t there a way to simply prevent the body from jumping up while still preventing it from scrolling !?

Detect device of where an Iframe is embedded

I understand that in javascript the best way to detect where a device is opened is using the size of the screen. The problem is that the project that I am working on will be embedded using an iframe and it’s size will be fix, and there might be a scenario where the size will pass as mobile size even though it is embedded in a web. Is there a known package for react to detect a device aside from the screen size, I tried detect-device package but it stills detect a web view the moment the view is shrink.

I tried using detect-device package and screen size solution