Cannot serve React app in NX-jsx is not currently enabled

I created a react app in a NX workspace using nx g @nrwl/react:application --js --unitTestRunner=none --e2eTestRunner=none my-project

Then I developed my project. Finally when I want to run my project using
nx serve my-project I get following error:

Syntax error: Support for the experimental syntax 'jsx' isn't currently enabled

I realized that it is related to babel configuration of project so I
installed @babel/preset-react @babel/preset-env and replaced content of
.babelrc file

configuration before any change:

{
  "presets": [
    [
      "@nrwl/react/babel",
      {
        "runtime": "automatic",
        "importSource": "@emotion/react"
      }
    ]
  ],
  "plugins": ["@emotion/babel-plugin"]
}

.babelrc after installing packages

{
  "presets": [
    "@babel/preset-env",
    "@babel/preset-react"
  ]
}

I also changed jsx property in compilerOptions of tsconfig.json from
"react-jsx" to "react"

but when I run nx serve my-project again, I get that error again.

What should I do? Is there any solution?

How Can I? Set foo.style.display where foo is the element name based on a js variable rising in increments

I have my program set up so that it autogenerates HTMl and places it into the webpage. Each introduction of new HTMl is given a new ID following along which increment it is at e.g <div id = "genQuestion0"> <div id = "genQuestion1">etc.

The inital div’s have all been set through CSS as no display

[id^="genQuestion"]{
    text-align: center;
    display: none;
} 

The first question id = genQuestion0 has been set that upon generation its display is set to block.

How can I make it so that when a button is pressed the previous questions display is changed to none and the next one is set to block.

This is what I have currently for my function but it does not work.

var countclicks = 0;

const nextQuestion = () =>{
  var elementName = `genQuestion${countclicks}`;
  var elementNameNeg = `genQuestion${(countclicks - 1)}`;
  elementName.style.display = "block";
  elementNameNeg.style.display = "none";
  countClicks ++;

}

Yup array of object validation

const initialValues = {
graphics: {
  screenshots: [
    {
      url: url,
      path: path,
      order: 0,
      size: 100,
      width: 1280,
      height: 720
    },
    {
      url: url,
      path: path,
      order: 1,
      size: 100,
      width: 1280,
      height: 720
    },
    {
      url: url,
      path:path,
      order: 2,
      size: 100,
      width: 1280,
      height: 720
    },
    {
      url: url,
      path: path,
      order: 3,
      size: 100,
      width: 1280,
      height: 720
    },
    {
      url: url,
      path: path,
      order: 4,
      size: 100,
      width: 1280,
      height: 720
    }
  ]
}

}

Facing issue with the validation. What I want is to validate is minimum 2 object having screenshot URL value then its should pass validation. If more then 2 it should fail, value should be irrespective of the order.

How to use JavaScript to set an attribute if a condition exists?

In the snippet below, I’m creating an array of all panels and all links within those panels.

Then, for each panel with the class of active, I want all the links to be set to tabindex="0". For all other links, I want tabindex="-1".

In my example, I don’t understand why all links are set to tabindex="-1", when one of the panels has the active class. Why isn’t it set to tabindex="0"?

const panels = document.querySelectorAll('.panel');
const links = document.querySelectorAll('.panel a');
panels.forEach(function(panel) {
  if (panel.classList.contains('active')) {
    Array.prototype.forEach.call(links, link => link.setAttribute('tabindex', '0'))
  } else {
    Array.prototype.forEach.call(links, link => link.setAttribute('tabindex', '-1'))
  }
})
<div class="panels">
  <div class="panel active">
    <p>Hello <a href="#">World</a>. I am <a href="#">with</a> you.</p>
  </div>
  
  <div class="panel">
    <p>Hello <a href="#">World</a>. I am <a href="#">with</a> you.</p>
  </div>  
</div>

Adding a select all, uncheck all function to my filter checkboxes react+typescript

I created this function which is a filter with checkboxes.
How can I add the functionality where you can check all/uncheck all to my existing code, aslo adding typescript to it?

Any help is very appreciated!

function FilterCheckbox(props) {
  const wells = ["All","Legacy Wells", "Injection Wells", "Monitoring Wells"];
  const [checkedWells, setCheckedWells] = useState([]);

  const wellsProps = { wells, checkedWells, setCheckedWells };
  return (
    <div>
      <CheckedWells {...wellsProps} />
    </div>
  );
}

function CheckedWells(props) {
  const handleChecked = e => {
    const well = props.wells[e.target.dataset.id];
    let newCheckedWells = props.checkedWells.filter(item => item !== well);
    if (e.target.checked) newCheckedWells.push(well);
    props.setCheckedWells(newCheckedWells);
  };

  return (
    <div>
      {props.wells.map((well, id) => (
        <label key={id}>
          <input type="checkbox" data-id={id} onClick={handleChecked} /> {well}
        </label>
      ))}

      <p>{props.checkedValues}</p>
    </div>
  );
}
export default FilterCheckbox

How can I create a seed-based randomizer that will allow me to skip to any step at anytime?

// imagine i have a seed based random number generator
const list = []
for ( let i = 0; i < 24; ++i ) {
  list.push( Math.randomIn( 0, 100 ) )
}
// it always outputs
[70, 58, 88, 80, 12, 91, 1, 21, 26, 61, 41, 83, 22, 29, 92, 87, 31, 16, 7, 39, 53, 31, 62, 55]

// however for my case, i need 8388608000000 values
// i would like to be able to have

getSeedBasedRNGByIndex( 2955246414062 )

// is there a way to skip ahead or go backward using a satisfyingly random seed based generator ?

In my cases, I have a need to quickly skip ahead in a seed based RNG. It definitely helps if I can also go backwards as well

How to use JavaScript to set tabindex on an anchor tag when a condition exists?

In the snippet below, if an element contains a specific class, then all links inside that element are to be set to tabindex="0", otherwise tabindex="-1".

I’m getting an error – Uncaught TypeError: links.setAttribute is not a function and I’m unsure how to fix this?

const panels = document.querySelectorAll(".panels");

Array.prototype.forEach.call(panels, (panel) => {  
  const links = document.querySelectorAll(".panel p a");
  
  if (panel.classList.contains("active")) {
    links.setAttribute("tabindex", "0");
  } else {
    links.setAttribute("tabindex", "-1");
  }
});
<div class="panels">
  <div class="panel active">
    <p>Hello <a href="#">World</a>. I am <a href="#">with</a> you.</p>
  </div>
  
  <div class="panel">
    <p>Hello <a href="#">World</a>. I am <a href="#">with</a> you.</p>
  </div>  
</div>

Print a div using jqeury

I have some coupons with print buttons. I want to print it on click.

<div class="promotions">
<div class="coupons"><a href="/coupo-1.jpg" data-fancybox="images"><img src="/coupo-1.jpg" alt="" width="900" height="1200" /></a>
<button class="btn printCoupon">Print Button</button></div>
<div class="coupons"><a href="coupo-2.jpg" data-fancybox="images"><img src="coupo-2.jpg" alt="" width="900" height="1200" /></a><button class="btn printCoupon">Print Button</button></div>
</div>
<script>
        jQuery(document).ready(function(){
            jQuery(".printCoupon").click(function () {
                let coupon = jQuery(this).closest('div.coupons');
                console.log(coupon)
                // Here I have div not a selector, so how can I print it
                jQuery(coupon).print();
            });
        })
</script>

The problem is that I am selecting the div which I want to print. But I have whole div not specific class or id, so how can I print that.

Trouble Running Nodemon

New to node.js, Been trying multiple methods of running my index.js on nodemon.
To start I ran these commands in the terminal (chronological order):

  1. sudo npm install nodemon -g
  2. npm install --save-dev nodemon
  3. nodemon index.js

This the error code I am getting:

jeff-tatlises193% nodemon index.js
Usage: nodemon [nodemon options] [script.js] [args]

  See "nodemon --help" for more. ```

Nodemailer works only locally in React App

I’ve followed a tutorial online, my goal was to make a form so users can send me an email directly from the web app and it works but only from my machine when I hit run on function in visual studio code. What should I do to make it works when I deploy it? Should I change something in package.json or maybe deploy that code separately and fetch from there? Or call it in some useEffect? Here is the code so you can get a picture.

const express = require("express");
const router = express.Router();
const cors = require("cors");
const nodemailer = require("nodemailer");
const app = express();
app.use(cors());
app.use(express.json());
app.use("/", router);
app.listen(5000, () => console.log("Server Running"));

const contactEmail = nodemailer.createTransport({
    service: 'gmail',
    auth: {
      user: "[email protected]",
      pass: "mypassword",
    },
    secureConnection: 'false',
        tls: {
            ciphers: 'SSLv3',
            rejectUnauthorized: false
        }
  });
  
  contactEmail.verify((error) => {
    if (error) {
      console.log(error);
    } else {
      console.log("Ready to Send");
    }
  });
  router.post("/contact", (req, res) => {
    const name = req.body.name;
    const email = req.body.email;
    const message = req.body.message; 
    const mail = {
      from: name,
      to: "[email protected]",
      subject: "Contact Form Submission",
      html: `<p>Name: ${name}</p>
             <p>Email: ${email}</p>
             <p>Message: ${message}</p>`,
    };
    contactEmail.sendMail(mail, (error) => {
      if (error) {
        res.json({ status: "Something went wrong, please try again." });
      } else {
        res.json({ status: "Message sent!" });
      }
    });
  });

Twitter bot sleeping on Heroku

I have a twitter bot running with PM2 in my Heroku dyno. My bot creates a long-live HTTP request to filter tweets. My goal is to keep this bot running 24/7 in order to fetch every tweet that matches the hashtags that I’m looking for.

My Twitter bot works fine but there’s one problem that is giving me a hard time to debug: The bot is sleeping and not fetching tweets after a certain period of time.

Some times the bot is working for few hours, sometimes for few days. It is not clear what’s wrong since I don’t have logs helping me here. Whatever is happening, it is happening outside of the parts of the code with console.log, nothing is being printed in the Heroku logs.

Here is the code of the stream used in my bot:

const stream = needle.get(streamURL, {
    headers: {
        "User-Agent": "v2FilterStreamJS",
        "Authorization": `Bearer ${token}`
    },
    open_timeout: 0
});

stream.on('data', data => {
    try {
        const tweet = JSON.parse(data)

        // Handles the Tweet
        handleTweet(tweet)

        // A successful connection resets retry count.
        retryAttempt = 0;
    } catch (e) {
        if (data.detail === "This stream is currently at the maximum allowed connection limit.") {
            console.log(data.detail)
            process.exit(1)
        } else {
            // Keep alive signal received. Do nothing.
        }
    }
}).on('err', error => {
    console.log(error)
    if (error.code !== 'ECONNRESET') {
        console.log('Error: ' + error)
        process.exit(1);
    } else {
        // This reconnection logic will attempt to reconnect when a disconnection is detected.
        // To avoid rate limits, this logic implements exponential backoff, so the wait time
        // will increase if the client cannot reconnect to the stream.
        setTimeout(() => {
            console.warn("A connection error occurred. Reconnecting...")
            streamConnect(++retryAttempt);
        }, 2 ** retryAttempt)
    }
});

return stream;

Most of the code was taken from Twitter v2 Examples so I posting only the part that I updated. I set the open_timeout to 0 in order to avoid Needle timing out the connection. Reading Twitter docs, they have mentioned they send a keep-alive signal every 20 secs to keep the connection alive.

This is my ecosystem.config.cjs config file for PM2:

module.exports = {
  apps : [
{
  name: 'discord',
  script: './app.js',
  instances: '1',
  exec_mode: 'cluster',
  env: {
    NODE_ENV: "development",
  },
  env_production: {
    NODE_ENV: "production",
  }
},
{
  name: 'twitter',
  script: './twitter.js',
  instances: '1',
  exec_mode: 'cluster',
  env: {
    NODE_ENV: "development",
  },
  env_production: {
    NODE_ENV: "production",
  }
}],

};

One weird thing is that running pm2 list doesn’t show any of these apps, even though both of them are running. One of my attempts was to use Heroku Scheduler to restart the twitter app every hour.

Thanks in advance

Conditionally pick a prop to use

const Component = ({

    const someBoolean 

    return (
          <Component
             prop1
             prop2

I want to use prop1 ONLY when someBoolean is true, otherwise prop2 should be used. What is the best way to do this ?

So say someBoolean is true I would have

const Component = ({

    const someBoolean 

    return (
          <Component
             prop1

Otherwise I would have

const Component = ({

    const someBoolean 

    return (
          <Component
             prop2

Swiper.js blocks page re-render on vercel

I have issue with swiper.js when I deploy my website on vercel. Swiper stops my website from re-rendering ( when I make change content stays the same ). On development environment everything works perfectly, but when I push it on vercel content stays the same. Here is my code:

import React from "react";
import Product from "../../components/PremiumProducts/Product";
// import { Swiper, SwiperSlide } from "swiper/react";
// import SwiperCore, { Autoplay } from "swiper";
// SwiperCore.use([Autoplay]);
// Import Swiper styles
// import "swiper/css";
export default function PremiumProducts(props) {
  const { data } = props;
  console.log(data);
  return (
    <>
      <section className="premium">
        <div className="premium__brands">
          <div className="premium__brands-content center-content">
            {/* <Swiper
              spaceBetween={10}
              slidesPerView={5}
              loop={true}
              autoplay={{ delay: 2000, disableOnInteraction: false }}
              breakpoints={{
                400: {
                  width: 400,
                  slidesPerView: 2,
                  spaceBetween: 5,
                },
              }}
            >
              <SwiperSlide>
                <img src="/Premium/Brands/ime.png" alt="" />
              </SwiperSlide>
              <SwiperSlide>
                <img src="/Premium/Brands/biooil.png" alt="" />
              </SwiperSlide>
              <SwiperSlide>
                <img src="/Premium/Brands/tuf.png" alt="" />
              </SwiperSlide>
              <SwiperSlide>
                <img src="/Premium/Brands/fedor.png" alt="" />
              </SwiperSlide>
            </Swiper> */}
          </div>
        </div>
        <div className="premium__products">
          <div className="center-content">
            <div className="premium__products-content">
              {data.map((product, i) => {
                return <Product key={i} {...product} />;
              })}
            </div>
          </div>
        </div>
      </section>
    </>
  );
}

export async function getStaticProps() {
  const resp = await fetch(`${process.env.SERVER_API}premium-products`);
  const data = await resp.json();

  return {
    props: data,
    revalidate: 1,
  };
}