Is there any way we can use .cshtml partial view in a React web application?

I am working on a application that is built using the razor pages, react and angular, the basic design layout of the application is same, I have a problem where I need to use a dropdown component that was originally written for the MVC part of the application (in a .cshtml file) within my React application.

  • What have I tried so far?

Using this article, I am returning the _dropdown.cshtml partial view as a string and then appending it in my react web application as:

<div dangerouslySetInnerHTML={{ __html: this.state.partialView }}></div>

</div>

However, the problem is that this dropdown does not collapse or expand. (this dropdown is based on the Bootstrap collapse). I suspect that Bootstrap framework binds its events to the DOM, whereas in the React application, events are bound to the Virtual DOM, which is managed by the ReactDOM.

<a class="btn btn-primary" data-toggle="collapse" href="#collapseExample" role="button" aria-expanded="false" aria-controls="collapseExample">
    Link with href
</a>

Moreover this _dropdown.cshtml file is also using some code written in many separate JavaScript files, How can I make this appended code in my react application to use those external scripts too?

tl;dr I want to render C# partial views in my react web application and want to them to work same as they would work in an MVC application.

Spread operator is too slow

How to increase the execution time of spread operator in JS? I need to add an object to an array of objects, but spread operator and push methods are to slow, because the data is too big. For example I have an array of objects like this and I need to add one/two/three/etc more objects to the array to update the state.

{
  "category": 64,
  "createdAt": "2023-06-06T09:12:34.997Z",
  "id": 297,
  "logo": "49.png",
  "name": "Center",
  "publishedAt": "2023-06-06T09:12:34.995Z",
  "subed": true,
  "table_name": "type",
  "updatedAt": "2023-06-06T09:12:34.997Z"
}

For now I’m doing it like that:

setState([...oldState, newItem])

But theres a visible delay between action (click f.e.) and the update of state

Javascript error handling, error message is empty

I’m trying to add error handling to my submit form, but I’m not getting any error messages back..
There is a field for a url and when this url is set, a preview element loads this file and shows the file in the preview.

This function returns errors if there are any and that part works, but with the information I found online the message should be inside event.target.error/event.target.message, but both these variables are undefined..

$('.preview-element', '.file-upload').on('error', function(event){
    ...
});

Yup error this must be a `object` type, but the final value was: `null`

I have a validation schema defined using Yup as below

export const mySchema = {
    ['add-record']: yup.object().shape({
        'myId': yup
            .string()
            .nullable()
            .required()
    })
}

On click of some button, I invoke the validation as below;

await mySchema['add-record'].validate(props.formRef.current.getValues("myId"), { context: { other: 4 } });

props.formRef.current.getValues(“myId”) is actually mapped to a textbox on the UI and as soon as I enter 123456789 and invoke the validation, I get an error saying;
this must be a object type, but the final value was: null (cast from the value "123456789").

Not sure why it is saying the final value is: null

Need help to make a request properly via the parameters

This is the first time I have to do this, and I’m really struggling.

To be short i reveive some data from my form, parse all data, and redirect to a url with the data parsed.

const tags = qs.stringify({tags: tabTags})
    const ingredients = qs.stringify({ingredients: tabIngredients})
    const name = qs.stringify({name: data.name})
    const url = `/recipes/all/search?${tags}&${ingredients}&${name}`;
    navigation(url);

We can already see that the code is not the best code ever..

URL look like : “http://127.0.0.1:5173/recipes/all/search?tags%5B0%5D=Vegan&tags%5B1%5D=Healthy&ingredients%5B0%5D=Courgette&name=ss”

Now, I come on this page

export default function RecipeSearch() {
    const [searchParams, setSearchParams] = useSearchParams()
    const queryParameters = new URLSearchParams(window.location.search)
    const tags = queryParameters.getAll("tags");
    const name = queryParameters.get("name");
    const ingredients = queryParameters.getAll('ingredients');
    const {data, isError, isLoading } = useFetchRecipe({tags:searchParams.getAll('tags'), recipe:searchParams.get('name'), ingredients:searchParams.getAll('ingredients')})
    if (isLoading) {
        return <p>Wait...</p>
    }
    if (isError) {
        return <p>Error ! </p>
    }
    return (
        <div className="flex flex-col mt-20 -ml-14">
            { console.log('tags',tags )}

        {data.map((recipe) => (
            <Recipe {...recipe}/>
        ))}
       
        </div>
    )
}

I want to retrieve the params and give them to “useFetchRecipe” and finally do my request.
But i can’t retrieve the url.
I really don’t know how to do this “proprely” with a hashed url as I showed above.
Thanks a lot if anyone can help me !

Already tried to get the url params with some techniques but none works

Nextjs, TypeError: api.createContextKey is not a function

(https://i.stack.imgur.com/jA9NV.png)

TypeError: api.createContextKey is not a function
at Object. (C:UsersKrathish skDesktopNextJS_UdemyProjectsmy-blogsnode_modulesnextdistserverlibtracetracer.js:60:27) at Module._compile (node:internal/modules/cjs/loader:1105:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Module.require (node:internal/modules/cjs/loader:1005:19)
at require (node:internal/modules/cjs/helpers:102:18) at Object. (C:UsersKrathish skDesktopNextJS_UdemyProjectsmy-blogsnode_modulesnextdistserverload-components.js:27:17)
at Module._compile (node:internal/modules/cjs/loader:1105:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10)

Could anyone please help me with this error !!

Divs and content of divs are overlapped when using position absolute to a div in web view

I created a design. in that three images inside a parent div are stacked to each other with position absolute. when i created a mobile responsive view for that design the image’s div vanished and the other div overlapped it. the images inside that div overlapped other divs. how can i create a responsive design while using position absolute in web view?

i tried everything for the above mentioned problem but nothing happened

stripe customer portal link won’t open in iframe

const cust_portal = https://billing.stripe.com/p/session/test_YWNjdF8xTkNuYmRIeW9HS21GdWpMLF9PMXpTb3NwUsdfdsjNFRmRGc5dThZd3hHU2VmdWpZ0100NmxjzxnT
<iframe src={cust_portal}></iframe>

The result is a link refused to connect error:

Refused to frame 'https://billing.stripe.com/' because an ancestor violates the following Content Security Policy directive: "frame-ancestors 'none'".

The link works if I open in a new tab like so:

window.open(cust_portal)

Why is the list not updating when i run this edit function?

editItemFRM(item) {
        this.nextView("mediaItemEditview", { 
            item: item,
            actionBindings: {
                submitEditForm: ((event) => {
                    event.original.preventDefault();
                    item.update().then(() => {
                        this.updateInListview(item._id,item);
                    });
                })
            }

        });
    }

i have an easier version of the edit function where you open an popup window were you can change the name of the listitem. There it works just fine. i do not understand why it won’t work in the other one, there i have to refresh the page to see the changes

Could you please help on reactjs?

some.js file
const regexPattern = process.env.REACT_APP_REGEX_PATTERN;
const offername = offernames === undefined ? undefined : (process.env.REACT_APP_PRODUCTCATLOG_SEARCH_AUTOADD_WILDCARD === “Y” ? “*” + offernames.replace(new RegExp(regexPattern, “g”), ” “) : offernames);

env file
REACT_APP_REGEX_PATTERN=[^äÄöÖåÅ’A-Za-z0-9]

replace should work and all special characters should replace with space

Focusing an overflowing div’s element on a frame

This is a rather complex issue I’m facing and it’s hard to describe, but I’ll do my best.

I have the following HTML code:

<div id="exploration-mapPanel" class="blueBorder">
    <div class="exploration-repositionMap"></div>
    <div class="exploration-mapContainer">
        <div class="exploration-map" style="width: 1440px; height: 1440px;">
            <div id="cl-1395108748101" class="map-roomContainer" style="top: 680px; left: 680px;"></div>
            <div id="ch-605075680943" class="map-roomContainer" style="top: 640px; left: 680px;"></div>
            <div id="ch-118749262187" class="map-roomContainer currentRoom" style="top: 720px; left: 680px;"></div>
            <!-- There are a few dozens of these "map-roomContainer", randomly generated -->
            <!-- and randomly positioned when the page is loaded. However, only one of -->
            <!-- them has the currentRoom class -->
        </div>
    </div>
</div>

The main feature of this code is that, through JS events, the player is able to drag around, zoom in and zoom out of the map (a bit like on Google Maps). How it works: the “exploration-map” is a large div that is contained into a much smaller div (exploration-mapContainer) that acts like a frame. “exploration-map” is absolutely positioned, and events change its left and top properties when the user holds left click and moves his mouse.

I managed to achieve that, but see the “exploration-repositionMap” button? That’s my issue.

Every time the page is reloaded, one of the many “map-roomContainer” divs will have an extra class named “currentRoom” which indicates the player’s current position.

I’d like the “exploration-repositionMap” button to center the map, in the “exploration-mapContainer” frame, on the currentRoom div when it’s clicked. I’ve tried many things, but since the “exploration-map” size is random, and the position of the “currentRoom” is random as well, I did not manage to come up with anything that works.

I hope my problem is clear and please don’t hesitate to ask questions if you need more details.

Here is a link to a simplified CodePen that pretty much illustrates the issue.

TL;DR: Tried to make the “currentRoom” div appear in the center of the “mapContainer” frame when clicking the “repositionMap” button.

“JSX element ‘div’ has no corresponding closing tag.”

import { useEffect, useState } from “react”
import Bloglist from “./BlogList”;

const Home = () => {

const [blogs, setBlogs]= useState(null);
const [isPending, setIsPending] = useState(true)


useEffect( () => {
    setTimeout(() => {
        fetch('http://localhost:8000/blogs')
        .then(res =>{
            return res.json();
        })
        .then(data=>{
            
            setBlogs(data)
            setIsPending(false)
        })
    }, 1000);
   

},[]);

return ( 
    <div className="home">
        {isPending && <div>Loading...<div/>}
        {blogs && <Bloglist blogs={blogs} title="All blogs!"/>}
    </div>
 );

}

export default Home;

I got an error message when I tried to run the code.
“JSX element ‘div’ has no corresponding closing tag.” this is the error message. What should I do?

I was trying to learn conditional loading message.

iFrame’s video refusing to play on iOS

I have this code below that works perfectly on desktop (I replaced the main url and the poster with demo ones):

<div style="position: relative; padding-top: 56.25%;">
  <iframe id="video-frame" src="demo-video-url.com?preload=true&poster=video-poster.jpg%3Ftime%3D%26height%3D600&controls=false" style="border: none; position: absolute; top: 0; left: 0; height: 100%; width: 100%;" allow="accelerometer; gyroscope; autoplay; encrypted-media; picture-in-picture;" allowfullscreen="true"></iframe>
  <div class="overlay">
    <button class="custom-button" id="cta-button">Join Stream</button>
  </div>
</div>
<script>
document.getElementById("cta-button").addEventListener("click", function() {
    var iframeSrc = document.getElementById("video-frame").src;
    document.getElementById("video-frame").src = iframeSrc + '&autoplay=true'; 
    this.parentElement.style.display = 'none';
});
</script> 

However, it’s refusing to play on iOS (iPhones for example), is there any workaround to it?

Issue with CURL File Upload

I have a problem using CURL File Upload and PSPDFKit API (https://pspdfkit.com/api/pdf-watermark-api/) while uploading documents to stamp in my website. This is what I’ve tried,

<?php

$FileHandle = fopen('result.pdf', 'w+');

$curl = curl_init();

$instructions = '{
  "parts": [
    {
      "file": "document"
    }
  ],
  "actions": [
    {
      "type": "watermark",
      "image": "logo",
      "width": "25%"
    }
  ]
}';

curl_setopt_array($curl, array(
  CURLOPT_URL => 'https://api.pspdfkit.com/build',
  CURLOPT_CUSTOMREQUEST => 'POST',
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => '',
  CURLOPT_POSTFIELDS => array(
    'instructions' => $instructions,
    'document' => new CURLFILE('../assets/images/excellerr.pdf'),
    'logo' => new CURLFILE('../assets/images/30years.png')
  ),
  CURLOPT_HTTPHEADER => array(
    'Authorization: Bearer {API_CODE}'
  ),
  CURLOPT_FILE => $FileHandle,
));

$response = curl_exec($curl);

curl_close($curl);

var_dump($curl);

fclose($FileHandle);

the error I got,
resource(5) of type (Unknown)
I think there’s a problem in my CURL or the API itself. Thanks for the help.

How to use Dynamic array in useEffect hook in React?

i want to use a dynamic array as input in dependency array of useEffect hook. But the array is going as a string and so not triggering the hook in the correct way.

const [formData,setFormData] = useState({
    name: '',
    age: '',
    place: ''
})

let receivedDynamicArray = ['formData.name','formData.age']

useEffect(()=>{
    // do something
},[...receivedDynamicArray])

Has anyone faced such an issue before?. If yes please share how you resolved this.
Thank you.

i tried using the eval and JSON.parse functions for the dynamic array to make it non-string, but that didnt work either.