Set style of html element by targeting it’s id in Blazor

Say I have an element in Blazor. I want to set the elements style based on the value of the input field in Blazor. I am aware that you can do this by using if else blocks in the html code however I want to avoid this as it grows the code base extremely quick. A function would be better which evaluates the incoming object and styles it.

for instance if I have the element below which passes a value the value is passed to a function.

<th><InputText placeholder="First Name" id=FirstName @bind-Value="@filterModel.FirstName">First Name</InputText></th>

Function

    private async void UpdateVisibleData(object sender, FieldChangedEventArgs e){
        Console.WriteLine(e.FieldIdentifier.FieldName + " Change Detected");
        var fieldChanged = e.FieldIdentifier.FieldName;
        var IsEmptyString = FindEmptyStringInField(filterModel, fieldChanged);
        if(IsEmptyString){
            element.style.setProperty('--my-variable-name', 'hotpink');
           }
        }

I havent been able to get the style.setproperty part to work. not sure what other methods there are. Open to JSInterop. preferrable though if I can target the style.setproperty function and get this working.

React useScript calls a third party script doesn’t work on some domain

I’m calling this script https://cdn.jsdelivr.net/npm/@sheerid/[email protected]/sheerid.js in useScript, like:

const [sheerIdJSLoaded, sheerIdJSError] = useScript(
    "https://cdn.jsdelivr.net/npm/@sheerid/[email protected]/sheerid.js,
    {
      attr: {
        crossOrigin: "anonymous"
      }
    }
  );

and it is working fine on a particular domain, like stage.domain.com, but when executing it on fr.stage.domain.com the script fails to load. What could be the problem here, appreciate any help.

how to change the value of the sate in react

I’m a beginner in using states in reactjs so im sorry if my question shouldn’t be asked in the right spot.Using React js, Node js and mongodb

So i created a constructor and initialized a variable called val inside it and passed that variable in a value property in a textarea tag so the user would enter somthing and it would be saved in the val variable (im not sure if thats the right way of doing it, so thats why im asking!). Also, I created a function called handleSubmit that would get the variable val and save it in mongodb, and i called that function in the button the user supposed to click when he passes in somthing. But all that doesn’t seem to be working with me.

Here is my ping.js file:

class Pingbutton extends React.Component {
  constructor(props) {
    super(props);
    this.state = { val: "Ford" };
  }

  handleSubmit = () => {
    // if we get state error then we need to put it in a claa and call the constructot and then call the function using this.state.the name of the function
    console.log("its running 1");
    let databody = {
      message: this.state.val,
    };
    console.log(" the message is :" + databody.message);
    console.log(" the message is :" + this.state.val);
    return fetch("http://localhost:5000/stored", {
      method: "POST",
      body: JSON.stringify(databody),
      headers: {
        "Content-Type": "application/json",
      },
    })
      .then((res) => res.json())
      .then((data) => console.log(data));
  };
  render() {
    return (
      <div className="ok2">
        <textarea
          className="message"
          type="text"
          placeholder="Write me somthing!. Also, double click to ping:) "
          value={this.setState.val}
        ></textarea>
          <button
            className="button"
            onClick={() => {
              this.magic();
              this.handleSubmit(); //animation + //pinging the phone
              // this.handleButtonClick(); //setVal(() => ""); //sets the value of the box to empty
            }}
          >
          </button>
      </div>
    );
  }
}

export default Pingbutton;

and this is the back-end (nodejs) index.js file:

const express = require("express");
const cors = require("cors"); // Importing cors
var request = require("request");
const dotenv = require("dotenv");
const port = 5000;
var request = require("request");
var util = require("util");
const connectDB = require("./config/db");
require("dotenv").config({ path: "./config/config.env" });


const app = express();
dotenv.config();
connectDB();

app.use(cors({ origin: "http://localhost:3000" }));
app.get("/", (req, res) => {
  res.send("Hey there!");
});

app.use(cors({ origin: "http://localhost:3000" }));
app.get("/Pinged", function (req, res) {
  find_my_iphone("[email protected]", "Faresomar123", "Omar");
  res.send("Pinged!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
});

app.use(cors({ origin: "http://localhost:3000" }));
app.post("/stored", (req, res) => {
  console.log("its running 2: " + req.body);
  db.collection("quotes").insertOne(req.body, (err, data) => {
    if (err) return console.log(err);
    res.send("saved to db: " + data);
  });
});

app.listen(port, () => console.log(`Example app listening on port ${port}!`));

I have been getting Ford in the two console in the front-end after typing somthing in the box and clicking the button (excuting the handleSubmit) function). I tried doing this.state.val but didnt work then i changed it to this.setState.val and didnt work either.

I would appreciate the help.

THANK YOU!

history.push and state resetting

Using props.history.push step forms is messing up my state. I have a mult-step form and keep the current step in the state of the component. In addition, between steps I need to change the URL in the same component, so I have a conditional route working. In between next and previous I am calling a function to update the current step, the current step counter is working like a charm when clicking through the steps. The issue comes when needing to change the URL.

Using props.history.push(route) is re-rendering the component and the current step counter is lost and set back to 0 (its initial value). How can I avoid to loose the counter in the state? The code snippet is the following:

const StepForm = (props, state, next, prev,) => [
  {
    title: "Step 1",
    content: <StepOne />,
    buttons: [
      null,
      <Button onClick={() => next_step()}> Next </Button>,
    ],
  },
  {
    title: "Step 2",
    content: (<stepTwo/>),
    buttons: [
      <Button
        onClick={() => {
          next_step();
          props.history.push(
            `/items/${item.id}`
          );
        }}
      >
        Next
      </Button>,
    ],
  },
  {
    title: "Step 3",
    content: <StepThree />,
    buttons: [
      null,
      <Button onClick={() => next_step()}> Done </Button>,
    ],
  },
];


export class ItemPage extends Component {
  state = {
    step: 0,
  };
  
  next_step = () => this.setState((prevState) => ({ step: prevState.step + 1 }));
  prev_step = () => this.setState((prevState) => ({ step: prevState.step - 1 }));
  
  render() {
    const Forms = StepForms(
      this.props,
      this.state,
      this.next_step,
      this.prev_step);
    
    <Steps step={this.state.step}>
       {Forms.map((step) => (
         <Steps.Step key={step.title} title={step.title} />
       ))}
    </Steps>
    <Col span={24}>
      <div>{Forms[this.state.step].content}</div>
    </Col>

The issue is that component is re-render with props.history.push(), and step variable in state is reset to 0. How should I avoid resetting state?

Thanks

MUI – impossible to override Text type? “Property ‘link’ does not exist on type ‘TypeText'” when using custom theme

I’m trying to add a “link” property to “text” within palette. so that I can do color: theme.palette.text.link. The docs mentions I need to augment the type, which I’m doing. This works for their example of adding the status.danger property.

However, when trying to augment the text, this simply doesn’t work. i get the following error: Property 'link' does not exist on type 'TypeText'.

Is there a different type I need to augment?

THIS WORKS (but it’s not what i need):

declare module '@mui/material/styles' {
  interface Theme {
    status: {
      danger: string;
    };
  }
  // allow configuration using `createTheme`
  interface ThemeOptions {
    status?: {
      danger?: string;
    };
  }
}

THIS DOES NOT WORK:

declare module '@mui/material/styles' {
  interface Theme {
    text: {
      link: string;
    };
  }
  // allow configuration using `createTheme`
  interface ThemeOptions {
    text?: {
      link?: string;
    };
  }
}

Here’s the type I’m trying to augment

CSS: Fixed header table – how to not focus on the out-of-view row behind the fixed header when scrolled up?

Background

I have a table with fixed header (fixed <th>s to be exact), with vertically scrollable content. You just scroll up and down with the scroll bar as usual, and you can scroll up and down with up/down arrow keys. I am highlighting where is the currently focused row with a red outline. See for yourself below.

Problem

The problem is when scroll down a bit and try to go up with up arrow key, it reaches the top row under the fixed header. the top row is not visible, so focusing on that when scrolling up with up key is not favorable.

Question

How do I prevent focusing on a “out-of-view” row? Ideally I want it to scroll further up if it reaches the top last visible row, not the one behind the fixed header. Maybe I should do something with the header?

Minimum reproducible code

Here is the JSFiddle code

Reversing a moving object in JS

My task is to create a ball and make it move back and forth across the screen. I have made it move in one direction but am having issues making it go in reverse.
Here’s what I have thus far:

function moveBall() {
  positionX = positionX + velocity;
  ball.style.left = positionX + 'px';
  let reserve = false
  if (positionX = 20000 + 'px') return;
  !reverse;
}

The if statement only stops the ball at a certain point but doesn’t make it turn around.

I’m sure it’s something really simple that I’m just overlooking, especially at this point because I’ve been googling the hell out of this, so if anyone can give a noobie a hand that would be much appreciated!!

Find ‘most clicked’ variant in an array of objects, given a nested array of variants in Javascript

I have an array of objects called articles. An article has 3 important properties. name, clicks, and variants. The variants property is also an array of objects that contain name (It corresponds to an article in the array articles). How do I find each article’s most clicked variant?

Input:

[
 {name: article1,
 clicks: 10,
 variants: [article2, article3]},

 {name: article2,
 clicks: 7,
 variants: [article1, article3]},

 {name: article3,
 clicks: 15,
 variants: [article1, article2]},

 {name: article4,
 clicks: 3,
 variants: [article5]},

 {name: article5,
 clicks: 6,
 variants: [article4]},
]

Desired output:

{name: article1,
clicks: 10,
variants: [article2, article3],
mostClickedVariant: article3}

{name: article2,
clicks: 7,
variants: [article1, article3],
mostClickedVariant: article3},

etc. for each article

Nodejs Difficulty using eval inside class

I’m having trouble using eval in my js file (class).

When I develop a code globally it works (Ex 1).

Now when I use eval inside the class it doesn’t work (Ex 2)

Code Ex 1 ->

var s = "function teste() {console.log('testando')}"
eval(s)

this.teste();

**Code Ex 2 -> **

class Oi {

  constructor() {
    this.s = ""
    this.t = ""
  }
  
  run(){
    this.s = "function teste() {console.log('testando')}"
    eval(this.s)
    
    this.teste();
  }
}

let o = new Oi();
o.run();

How to make a black and white two column alternating grid with javascript

I am mapping through an array and want the output to be the following:

Array.from([1,2,3,4,5,6,7,8,9,10]).map((number, index) => console.log(index))

// 0-white 1-black
// 2-black 3-white
// 4-white 5-black
// 6-black 7-white
// 8-white 9-black

How can I do this using the index of Array.map?

For context, I am mapping through a list of items to display on a two column grid. I need to use JS, therefore the index needs to infer the correct color and can’t use CSS in this scenario.

I can’t for the life of me figure out the math logic to get the color correct.

How To Write a HTML Interpreter

I’m looking for a way to convert strings with the following pattern to a valid html. What’s the best approach for this?

var input = `
tag:html
    tag:div
        Hello
        tag:span
            World
`
// expected output: <html><div>Hello <span>World</div></html>

How to type hint specific objects in function argument

Suppose I have some function:

const someFunc = (input) => {// do something}

Where I know the input is an object that will have the property thing, ie. in the function I might check what input.thing is. How do I type hint the function when I declare it? I tried something like:

const someFunc = (input: { thing: string }) => {// do something}

But that doesn’t seem to work.

Updating object key value problem (Javascript)

When prod is pushed into prodObj, description in all other similar objects are updated to its last instance.
While prod itself is just fine and all keys description are with its own value

    let prodObj = [];    

for (let i = 0; i < product.length; i++){
    for (let j = 0; j < cartRegistry.length; j++){
        if ( cartRegistry[j].ProductId === (product[i]._id.toString()) ){
            
            var prod = product[i];
            prod.description = parseInt(cartRegistry[j].Quantity);
            
            console.log(prod);
            prodObj.push(prod);
        }
    }
}

prod ex:
_id: new ObjectId(“62a52831c42a0fb4730283f4”)
name: ‘RJ45’,
image: ‘cable.jpg’,
description: ‘2’,

_id: new ObjectId(“62a52831c42a0fb4730283f4”)
name: ‘RJ45’,
image: ‘cable.jpg’,
description: ‘1’,

ProdObj which was supposed to have the same values updates both description keys to 1, the last instance of it
Same with all other objects except they have different values

How to align left for Item1 and align right for Item2 & Item3 with MUI React?

I have one component, which have three different Typography components inside. I want to align “summary” to the left, and ‘miles’ and ‘duration’ to the right.

enter image description here

My code is below:

<Stack direction="row" spacing={1} divider={<Divider orientation="vertical" flexItem />} justifyContent='flex-end'>
    <Box align='left'>
        <Typography>Summary</Typography>
    </Box>
    <Box>
        <Typography sx={{ verticalAlign: 'middle', display: 'inline-flex' }}><DirectionsCarIcon /> {Math.round(totalDistance * 0.000621371192 * 10) / 10} Miles</Typography>
    </Box>
    <Box>
        <Typography sx={{ verticalAlign: 'middle', display: 'inline-flex' }}><AccessTimeIcon /> {totalDuration}</Typography>
    </Box>
</Stack>

I tried messing around with the justifyContent attribute but didnt work. Im pretty new to CSS and styling so im not sure what the best approach for this situation is. Any help or alternative suggestions are greatly appreciated 🙂