Override Mantine styles to only one element

In my React project, I am using Mantine’s library accordion in two different components: Search.jsx and Profile.jsx.

The point is I need to accurately customize its styles only in Profile so I inspected the element and discovered that the default Mantine’s class is named mantine-bgzycs. I applied styles to that class in Profile.css and it worked as I wanted.

The problem is that affects to Search’s accordion element too.

When I inspect I can see also a Mantine’s default ID but it changes dinamically.
I tried to envolve the elemen with a div and apply styles but most of them are overwritten by Mantine.

QUESTIONS:

Is there a way to apply styles only to one element of the same class?

Is there a way to restrict styles between React components?

Is there a way to access to Mantine’s source and edit accurately an element styles?

Thanks very much in advance!

In JavaScript, how do I get an asynchronous function called on a form submit to modify the DOM? [duplicate]

my code is as follows:

async function getPoll() {
    document.getElementById('poll').innerHTML = "Hello world";
}

The function in question is called when the user submits a form, utilizing the onsubmit event. However, when the user submits the form, the text “hello world” flashed briefly inside the h1 tags on my HTML page before disappearing entirely. How exactly do I resolve this problem?

Svelte/Express/Mongo: adding new blog post renders a new post component with undefined variables

I am attempting to modify code from this tutorial for my own site. I am running a mongodb atlas with a simple express app passing code between the mongo and my sveltekit front end.

below is the code for each post being rendered

    //posthome.svelte
    <script>

    import { onMount } from "svelte";
    import Postform from './Postform.svelte';
    const baseUrl = "https://islostexpress.herokuapp.com/posts/";

    let response = null
    let posts = [];
        
    let timerOK = false
    
    $: isLoading = !(response && timerOK)

    onMount(async () => {
        setTimeout(() => { 
        timerOK = true
        }, 900)

        fetch(baseUrl).then(callResponse => {
            // do your stuffs
            response = 'OK'
            console.log(response);
        })
        
    });

    onMount(async () => {
        let res = await fetch(baseUrl);
        posts = await res.json();
        let reversed = posts.reverse();
        console.log(reversed);
    })

    let addpost = ({ detail: post}) => {
        if (posts.find(p => p._id === post._id)) {
            const index = posts.findIndex(p => p._id === post._id);
            let postUpdated = posts;
            console.log(postUpdated);
            postUpdated.splice(index, 1, post);
            posts = postUpdated;
        } else {
            posts = [post, ...posts];
            
            
        }
      };

    let deletePost = async id => {
        if (confirm("Are You Sure?")) {
            let res = await fetch(`${baseUrl}/${id}`, {
                method: "DELETE"
        });
            posts = posts.filter(p => p._id !== id);
        } else {
            alert("Your Post is safe!!");
        }
    };

    let editPost = {
        title: "",
        description: "",
        url: "",
        submitter: "",
        id: null,
    };
    let editPostDetails = async post => {
        editPost = post;
        console.log(post);
    };


 </script>


<section class="mt-5 text-center">
    <div class="container">
      <div class="md:grid md:grid-cols-2">
        {#if isLoading}
            <div class="justify-center"><div id="loader"></div></div>
        {:else}          
        {#each posts as post}
            <div class="mb-9">
              <div class="">
                <div class=" text-3xl md:text-6xl text-green-500">{post.title}</div>
                <div class="">
                  <h5 class="">{post.description}</h5>
                  <p class=""><a href="{post.url}">{post.url}</a></p>
                  <p class="text-red-500">submitted: {post.created}</p>
                  <button class="btn btn-info" on:click={editPostDetails(post)}>Edit</button>
                  <button  on:click={deletePost(post._id)} class="btn btn-danger">Delete</button>
                </div>
              </div>
            </div>
          {/each}
          <div>
          </div>
        {/if}
      </div>
    </div>
  </section>
  <div>
    {#if isLoading}
    {:else}
      <Postform on:postCreated={addpost} {editPost} />
    {/if}
  </div>

here is the code for the postform.svelte component containing the fields to submit a new post

    <script>
    import { createEventDispatcher } from "svelte";
    const dispatch = createEventDispatcher();
    let data = {
      title: "",
      category: "",
      author: "",
      content: ""
    };
    const baseUrl = "https://islostexpress.herokuapp.com/posts/";

    let URL, method;

    let addNewPost = async () => {
      if (
        data.title.trim() === "" ||
        data.description.trim() === "" ||
        data.url.trim() === "" ||
        data.submitter.trim() === ""
      ) {
        return;
      }

      let loading = true;

      if (editPost._id) {
          URL = `${baseUrl}/${editPost._id}`;
          method = "PUT";
          console.log("pre", editPost);
      } else {
          URL = `${baseUrl}`;
          method = "POST";
          console.log("not", editPost);
          let newPost = editPost[0];
      }


      const res = await fetch(URL, {
          method, 
          headers: {
              "Content-Type": "application/json"
          },
          body: JSON.stringify(data)
      });

      const post = res.json();
      dispatch("postCreated", post);
      data = {
          title: "",
          category: "",
          author: "",
          content: ""
      };

      loading = false;
    };


    export let editPost;

    $: data = editPost;

    

  </script>
  
  <section class="mt-4">
    <div class="container text-center">
      <div class="row">
        <div class="col-md-5">
          <div class="card p-3">
            <form on:submit|preventDefault={addNewPost} class="flex flex-col items-center">
                <div class="form-group">
                  <label for="title">Title</label>
                  <input
                    bind:value={editPost.title}
                    type="text"
                    class="form-control"
                    id="text"
                    placeholder="Title" />
                </div>
                <div class="form-group">
                  <label for="title">Description</label>
                  <input
                    bind:value={editPost.description}
                    type="text"
                    class="form-control"
                    id="text"
                    placeholder="Description" />
                </div>
                <div class="form-group">
                  <label for="title">URL</label>
                  <input
                    bind:value={editPost.url}
                    type="text"
                    class="form-control"
                    id="text"
                    placeholder="URL" />
                </div>
                <div class="form-group">
                  <label for="content">Submitter</label>
                  <textarea
                    bind:value={editPost.submitter}
                    class="form-control"
                    id="content"
                    rows="3"
                    placeholder="Submitter" />
                </div>
                <div class="text-center">
                  <button type="submit" class="btn classic text-center text-6xl text-red h-12 w-15 px-6 m-2 inline-flex items-center">
                    {editPost._id ? 'Update' : 'Submit'}
                  </button>
                </div>
              </form>
          </div>
        </div>
      </div>
    </div>
  </section>

Basically everything works except when I submit a new post, the card that is rendered on as the newest entry on posthome.svelte returns undefined variables. If i refresh the screen it will reping the server and return the text that i had previously entered with the undefined card gone.

How can i get rid of this undefined issue? is there a way to populate this card with the data i’m sending to the server at the same time?

let me know if you need more info or code from me

How to upload and display image using javascript, without predefining the “src” attribute?

Before diving deep into the course of the day, it is of importance you understand the following concepts.

Ok, I started off this particular study because I was stucked on a project, it was in a way very embarassing cause it took me hours to even figure out the best google search or even find the answer. I decided to document all what i gained from this particular study and share it, as it might be of immense help to you people out there.

Topic: Uploading an image through an input tag, creating an src for it and formating it.

Keywords are; DOMString, change, input, required, accept, capture, multiple, files, value.

Value: A file input value attribute contains the DOMString that represent the path to the selected file. if the user selected multiple files, the value represents the first file in the list of files they selected.

The Value if read with input.value has a prefix like C:fakepath… This saves the file structure of the user from malicious software with intentions of accessing the users content.

Format of input

 <input type="file" id="inputImage" accept="image/png, image/jpg" capture="" value="src" />

type: This gives the input tag a direction and line of action which is accessing files.

id: This is used by javascript or css for accessing and manipulating the input tag.

accept: This specifies the particular kind of file type the file input should accept. Various types are seperatied with commas like the example above. the file accepts only png and jpg files.
An example of a tag that accepts word documet is

<input type="file" id="pickDocument"
  accept=".doc,.docx,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document">

capture: This attribute specify what camara would be used to capture the image or video data; if accept attribute is indicated as user the front camara would be used but if it is environment, the rare camara would be used. This also works on a microphone.

multiple: This is a boolean attribute that allows user to upload more than one file at a time.

files: This is embeded in the browser and every file uploaded using the <input type="file"/> appends itself to this array.

// 
var input = document.querySelector('#inputImage');
//listen out for the change activity

input.addEventListener('change', upLoadImage);

function upLoadImage() {

  var file = input.files;
  console.log(file)
  //If you successfully logged the above in the console, it means you got an object and means that you are on the right path.


  //append the div with the result

  var image = document.querySelector('.image')
  var newImage = document.createElement('img')
  //Declare attributes of img including src



  newImage.setAttribute('src', URL.createObjectURL(file[0]));
  //append the Image tag into the div with class image
  image.append(newImage);

  var name = document.querySelector('.name')
  name.append(file[0].name)
}
<label>Upload Image</label>
<input type="file" id="inputImage" accept=".png, .jpg" capture="" value="src" />

<div class="name">
  <div>

    <div class="image"></div>

I hope this would help you through.

Why does this negative lookahead Unicode regex not work in JavaScript when direct match does?

I am trying to validate for filename or directory portions of a string that will eventually be used in a URL and want to reject non Unicode plus other characters, the regex is returning null bytes.

Given this string as input:

զվարճ?անք9879#jhkjhkhl!kjljlkjlkjj()+======_ew.html

/(?![p{L}]|[p{N}]|[._-~])/gu

JavaScript returns correct invalid character matches, but is selecting a null byte for every character matched and not the full character.

If I run the opposite and try to match on characters that are ok instead of not ok:

/[p{L}]|[p{N}]|[._-~]/gu

JavaScript returns matches and selects each valid character as expected, no null byte matches.

Each pattern has the /u flag. I don’t understand the difference in behavior. Tested this in the latest Chrome (update 100 as of post date), Safari, and Firefox and they all behave the same. Is there some flag or operator that the first regex is missing or is this a JavaScript bug / limitation?

Process to translate a simplified lambda expression into javascript

Does the following seem like a good procedure to translate a simplified lambda expression into a javascript arrow function? If not, what might I be missing or overlooking?

SUCCESSOR FUNCTION -- λnfa.f(nfa)
  1. We will treat the λ symbol as a named function for convenience, so we have:

    const SUCC = ...
    
  2. All letters until the . are function arguments. Since we only allow one-arg functions, each must be curried, so we now have:

     const SUCC = n => f => a => ...
    
  3. The . represents the start of the function body:

     const SUCC = n => f => a => { ... }
    

    However, since we’re using an arrow function we can ignore that and so we’re still at:

     const SUCC = n => f => a => ...
    
  4. (a) Letters followed by an open parenthesis are copied over as-is, meaning the letter preceding the paren takes what is inside the parens as a function call:

     const SUCC = n => f => a => f(...)
    

    (b) Letters following an open parens are also copied over as-is:

     const SUCC = n => f => a => f(n ...)
    

    (c) Letters that are preceded by another letter are treated as a single-argument function param to the function on the left — that is, they are copied over as ( [letter] )

    const SUCC = n => f => a => f(n(f)(a))
    

Applying this to the function we started with and some helpers to print something for debugging:

const ZERO = f => a => a;
const incr = x => x+1;
const SUCC = n => f => a => f(n(f)(a));
console.log(SUCC(SUCC(ZERO))(incr)(0));
// 2

Support for the experimental syntax ‘jsx’ isn’t currently enabled when upgrading from Babel 6 to Babel 7

I’m trying to upgrade the react-text-mask library to Babel 7 and React 17.

For that I forked: https://github.com/text-mask/text-mask

here: https://github.com/tlg-265/react-text-mask-react-17

and then I tried to upgrade Babel with the following command:

$ npx babel-upgrade --write

You can easily install it by doing this:

$ git clone https://github.com/tlg-265/react-text-mask-react-17
$ cd react-text-mask-react-17
$ npm i

My problem is: When I run it with:

$ npm run react:dev

I get this error:

Support for the experimental syntax 'jsx' isn't currently enabled

as you can see here:

ERROR in ./react/example/index.js
Module build failed: SyntaxError: C:react-text-mask-react-17reactexampleindex.js: Support for the experimental syntax 'jsx' isn't currently enabled (6:3):

  4 |
  5 | ReactDOM.render(
> 6 |   <App/>,
    |   ^
  7 |   document.querySelector('#content')
  8 | )
  9 |

Add @babel/preset-react (https://git.io/JfeDR) to the 'presets' section of your Babel config to enable transformation.
If you want to leave it as-is, add @babel/plugin-syntax-jsx (https://git.io/vb4yA) to the 'plugins' section to enable parsing.
    at instantiate (C:[email protected]:72:32)
    at constructor (C:[email protected]:358:12)
    at Parser.raise (C:[email protected]:3334:19)
    at Parser.expectOnePlugin (C:[email protected]:3391:18)
    at Parser.parseExprAtom (C:[email protected]:12969:18)
    at Parser.parseExprSubscripts (C:[email protected]:12539:23)
    at Parser.parseUpdate (C:[email protected]:12518:21)
    at Parser.parseMaybeUnary (C:[email protected]:12489:23)
    at Parser.parseMaybeUnaryOrPrivate (C:[email protected]:12283:61)
    at Parser.parseExprOps (C:[email protected]:12290:23)
 @ multi main
webpack: Failed to compile.

Any idea on how to make it work?

My system is as follows:

$ node -v
v12.16.1

$ npm -v
6.14.8

Thanks!

Newb Javascript qns

I’m just starting to learn about Javascript.

I’ve noticed that in the console I am able to assign variables without using keywords let/const/var;

somewhat similar to python.

Why is this so, when all that is taught says we should write code like:
let variableName = value;

Thanks.

How to mock a nested function with Jest

I’ve tried a couple of approaches but I’m not sure if it’s possible to mock a nested function in Jest. I read the official docs where they use axios, but I’m trying to mock a function that is imported, not a module.

for example, I have some function A, and within A I call B. I want to mock B so that it returns true once and then false once.

B is a function I imported that I wrote in another file, and I’m testing A.

so far I have tried to import function B into my test file and create a mock of it, but I don’t think it’s working how I thought it would

for example I have tried this

import { b } from "../util"
jest.mock("b", () => jest.fn().mockReturnValue(true));

and then my tested file would be

function a() => {
  while b() {
    do something;
  }
}

should I rewrite my test or function I’m testing?

Can’t get JavaScript to post to table from form

One of our current assignments is asking us to grab some basic information from a form and then have it post to a table. I’m not sure where I went wrong getting the JS to append the table. I tried to follow what was in our book to get what I have now but something went wrong.

When the submit button is hit, the form clears and the url shows the data change but nothing is added to the table on the page.

 <script src="demographics.js"></script>
        <form action="#" id="demographics" method="get">
            <span>Name</span>
                <input type="text" id="name" name="name">
            <span>Address</span>
                <input type="text" id="address" name="address">
            <span>City</span>
                <input type="text" id="city" name="city">
            <span>State</span>
             <input type="text" id="state" name="state">
            <span>Zip Code</span>
                <input type="number" id="zip_code" name="zip_code">
            <span>Phone Number</span>
                <input type="number" id="phone_num" name="phone_num">
            <span>Snapchat</span>
                <input type="text" id="snapchat" name="snapchat">
            <span>Twitter Usernme</span>
                <input type="text" id="twitter" name="twitter">
            <span>Instagram</span>
                <input type="text" id="instagram" name="instagram">
            <span>Favorite Video Game</span>
                <input type="text" id="favorite_game" name="favorite_game">
            <button type="submit">Submit</button>
        </form>
        <ul id="data">
            <li>Name</li>
            <li>Address</li>
            <li>City</li>
            <li>State</li>
            <li>Zip Code</li>
            <li>Phone #</li>
            <li>Snapchat</li>
            <li>Twitter</li>
            <li>Instagram</li>
            <li>Favorite Video Game</li>
        </ul>
    let form = document.getElementById("demographics");
    let table = document.getElementById('data');
    
    form.addEventListener("submit", (e)=>{
        e.preventDefault();
        submit();
    })
    
    const submit =()=>{
        let name = document.getElementById("name").value;
        let address = document.getElementById("address").value;
        let city = document.getElementById("city").value;
        let state = document.getElementById("state").value;
        let zip_code = document.getElementById("zip_code").value;
        let phone = document.getElementById("phone_num").value;
        let snapchat = document.getElementById("snapchat").value;
        let twitter = document.getElementById("twitter").value;
        let instagram = document.getElementById("instagram").value;
        let game = document.getElementById("favorite_game").value;
    
        let array = [name, address, city, state, zip_code, phone, snapchat, twitter, instagram, game];
        array.forEach((item)=>{
            var li = document.createElement("li");
            var text = document.createTextNode(item);
            li.appendChild(text);
            table.appendChild(li);
        })
        form.reset();
    }

Million Dollar Homepage [closed]

I learned about the million dollar homepage a while ago and was wondering how something like that would even be coded.

How would you get each individual ad up (multiple images) in the appropriate spots and how do you know its 1 million pixels?

How to listen for location for realtime in react native

I am working on a location tracking application, I am prompting an error message when users are off their location. Implemented functionality working but I face one problem when the user turns off location from the top menu of the mobile app it not working but when I close an app it worked ( it the bacause I am using react native app state to check app is foreground or in the background ). What I want to achieve when users are off their location I want to listen realtime when location off I want to prompt message direct.

Here is implemented functionality

const _handleAppStateChange = async (nextAppState) => {
    console.log("22 app", appState);
    if (
      appState.current.match(/inactive|background/) &&
      nextAppState === "active"
    ) {
      getCurrentUserLocation();
    }
    appState.current = nextAppState;
    setAppStateVisible(appState.current);
  };