/r/reactjs

Photograph via snooOG

A community for discussing anything related to the React UI framework and its ecosystem. Join the Reactiflux Discord (reactiflux.com) for additional React discussion and help.

About:

A community for learning and developing web applications using React by Facebook.

Interested in building mobile apps using React Native? Check out /r/reactnative!


Code of Conduct

If you believe someone is violating the code of conduct, please report the post or message, or contact the mods.

1. Please be kind and courteous, friendly and professional

Be kind to your fellow human. There’s no need to be mean or rude, keep unstructured critique to a minimum. When providing help, answer their question before making stylistic or tool suggestions.

2. Harassment will not be tolerated

We all started somewhere, and we're all allowed to be who we are. We are committed to providing a friendly, safe and welcoming environment for all, regardless of level of experience, gender identity and expression, sexual orientation, disability, neurodivergence, race, ethnicity, physical attributes, religion, nationality, or other aspect of identity.

3. Avoid using an alias or display name that might be offensive

reddit has a long history of intentionally offensive usernames, but not here. Names that detract from a friendly, safe and welcoming environment for all will be addressed.

4. Respect that people have differences of opinion

Every design or implementation choice carries a trade-off and numerous costs. There is seldom a single right answer, and there are valid reasons to choose between a range of tradeoffs between tools, approaches, and patterns.

5. Posts must conform to our guidelines

If you join this community to take value rather than contribute, the community will quickly react as though you are an intruder. If you have a body of content you'd like to promote, our recommended way of doing so is to be an active and positive member of the subreddit. If someone has a question that you've created an external answer to, we'd love if you share it!

  1. Demo videos must be accompanied by source code, preferably in a runnable environment like Codepen, CodeSandbox, Replit, Glitch, etc.
  2. Please save portfolios for the weekly Sunday portfolio post.
  3. Posts should be original works.
  • Please do not dump raw AI output as a post or comment. If you share something from an AI, please also include which service it came from as well as an original thought, like why the response is trustworthy or details about how you prompted.
  • This subreddit is focused on technical discussion of React, for career discussion check out /r/cscareerquestions or #jobs-advice in Reactiflux.
  • Avoid commercial activity. /r/reactjs follows the Reactiflux policy on commercial activity.
    • This is a community, not a free audience. This is not a place for prominent commercial activities such as recruiting, lead generation, marketing, market research, or other solicitation, except in posts dedicated to that purpose.
  • If the question is primarily "how do I make this code work?", please post it in the monthly "Beginner's Thread", or ask in the help channels of the Reactiflux Discord

  • New to React?

  • Kent Dodds' Egghead.io course
  • Codecademy's React courses
  • Scrimba's React course by /u/bobziroll
  • Road to React by /u/rwieruch
  • Our monthly Beginner Q&A Thread!
  • This Month in React podcast
  • React Digest

  • Chat

    reddit is a great format, but sometimes you need to chat in real time. Reactiflux is our recommended Discord community.

    Project Ideas

    Get Your Next Project Idea Here

    Jobs

    Like building things? People want to pay you to build things! Join Reactiflux and check out #job-board (and the rules!)


    Outside Reddit


    Related Subreddits

    /r/reactjs

    399,695 Subscribers

    1

    How to add a ChatGPT Assistant (like Siri) into my React app?!

    I'm looking for a way to add something like Siri (powered by ChatGPT), into my React project.
    I recently tried out this package https://github.com/sista-ai/ai-assistant-react and was amazed by how easy it was to set up. Literally just a couple of imports, and it was up and running!

    However, I'm wondering if anyone else has tried this or if there are other similar tools out there. I'd love to compare experiences and see if there are other options that offer a similar plug-and-play experience. Any recommendations or insights would be greatly appreciated!

    0 Comments
    2024/05/16
    16:26 UTC

    1

    Any experiences with developing ERPs and related software?

    We’ve started on building an in-house ERP and are finding that some of these applications have a much larger scope than initially perceived. I’m trying to plan out some of our options right now and am wondering if anyone’s had experience in this space?

    One example is the accounting platform. We’ve looked into temporarily implementing this portion with other potential services (Quickbooks API), and are on the look out for accounting software we could deploy ourselves. Another example might be inventory/sales management system.

    We essentially want to get this ERP up and running, and then slowly build out those portions of the product that we will probably end up supplementing with external services in the meantime.

    Any insight would be much appreciated!

    0 Comments
    2024/05/16
    16:23 UTC

    1

    Remix (RR7???) .env handling with Vite

    We just dropped a new video today on how to handle your .env files with Remix (or soon to be react-router 7) and Vite

    We go over server/client sides and how to not leak your .env, all the approaches you can use, and what we recommend to do!

    Check it out here:

    https://youtu.be/7Yk2YjAJSRQ

    0 Comments
    2024/05/16
    16:17 UTC

    1

    Best tools for my next project

    I'm looking to create an embeddable web widget with react. Are there good guides I should reference or template code I can use? Appreciate the help!

    0 Comments
    2024/05/16
    15:20 UTC

    2

    ⚛️ React Conf 2024 - Day 1

    0 Comments
    2024/05/16
    15:11 UTC

    1

    The Frontend

    Welcome to El Frontend, your go-to channel in Spanish to learn and enhance your skills in web development! Here you will find tutorials, tips, and resources to master the world of frontend and stand out in the digital industry. Join our community and together, let's make the Hispanic community shine in the world of web development!

    https://youtube.com/@ElFrontend?sub_confirmation=1

    0 Comments
    2024/05/16
    14:49 UTC

    9

    Are HOCs (Higher Order Components) still a thing?

    I hate this pattern and reminds of when React didn't embrace yet a functional approach, I am brushing up on some React and Angular for some job interviews and I wonder if I should I even bother with HOCs....

    25 Comments
    2024/05/16
    14:40 UTC

    2

    How to write this hook with React v19?

    export const useAutosizeTextArea = (
      textAreaRef: HTMLTextAreaElement | null,
      value: string,
    ) => {
      useEffect(() => {
        if (textAreaRef) {
          // We need to reset the height momentarily to get the correct scrollHeight for the textarea
          textAreaRef.style.height = '0px';
    
          const scrollHeight = textAreaRef.scrollHeight;
    
          // We then set the height directly, outside of the render loop
          // Trying to set this with state or a ref will product an incorrect value.
          textAreaRef.style.height = scrollHeight + 'px';
        }
      }, [textAreaRef, value]);
    };

    This is now giving a warning:

    Mutating component props or hook arguments is not allowed. Consider using a local variable insteadeslint(react-compiler/react-compiler)

    3 Comments
    2024/05/16
    13:56 UTC

    1

    Horizontal parallax with GSAP and React.js

    I'm trying to re create this codepen but with horizontal scrolling instead of the vertical scrolling in the codepen. The thing is, I can't even make it work. I copied the pen, but it's not working in my react project.

    The codepen link and my code is in the following stackoverflow link:

    https://stackoverflow.com/questions/78490030/horizontal-parallax-with-gsap-and-react-js

    0 Comments
    2024/05/16
    12:57 UTC

    2

    How to use the build of one react app inside another react application?

    I have created a build of a react app and now I want to use it in another(parent) react app. But when I am trying to run the parent app it is throwing minified react error #299 that the div is not currently in the DOM. I have tried setting setTimeout but it still is not working

    export default function ChildComponent() {

    useEffect(() => { const loadScript = () => { // Create a script element const script = document.createElement("script"); script.src = childScript; // Replace with the correct path script.async = true;

      // Callback function to be executed after the script is loaded
      script.onload = () => {
        // After the script is loaded, mount the child app into the child-root div
        const childRoot = document.getElementById("child-root");
        if (childRoot && window.ChildApp) {
          // Ensure the child-root div exists and the child app is available
          window.ChildApp.mount(childRoot); // Assuming you have a mount function in your child app
        }
      };
    
      // Append the script to the document body
      document.body.appendChild(script);
    
      // Clean up function to remove the script element when the component is unmounted
      return () => {
        document.body.removeChild(script);
      };
    };
    
    // Load the script after 2 seconds
    const timeoutId = setTimeout(loadScript, 2000);
    
    // Clean up function to clear the timeout when the component is unmounted
    return () => {
      clearTimeout(timeoutId);
    };

    }, []); // Empty dependency array to run the effect only once

    return <div id="child-root"></div>; }

    1 Comment
    2024/05/16
    10:41 UTC

    6

    Is it necessary to use useCallback when accessing functions from custom react hooks?

    So I was learning about custom react hooks and almost all of the tutorials when returning functions from the hooks have them wrapped in useCallback and the reason given is that on each render, react creates a new reference to the functions which may cause existing functions to become outdated.

    But my question is, everytime the hook is created again, it will cause the component where it is accessed to render again as well. Will this not automatically update all the variables and the function references used inside the component? So we no longer have outdated references?

    7 Comments
    2024/05/16
    10:39 UTC

    12

    Should I simply use the 3rd party api calls directly from the frontend, or is it preferable to make them all go through the server, and let the server communicate with the 3rd party api?

    Let's say I have a book site, where a button fetches all books in a library and displays them (need to call the 3rd party api and doesn't need to communicate with the app's server) but also has requests where it gets the user's saved books, and extra data, which would require communicating with the app's server.I am confused if at the first example I should simply let the front end talk to the 3rd part api, or make it talk to the server's api and the server would talk to the 3rd party (maybe this is better so I keep the api key hidden)Thanks.

    17 Comments
    2024/05/16
    10:30 UTC

    1

    Add Maps to a React.js application using Leaflet.js and OpenStreetMap

    1 Comment
    2024/05/16
    10:20 UTC

    2

    Difference between ways to render children

    const children = () =>  <div>children</div>
    //1
    const parent = () =>  <div>{children}</div>
    //2
    const parent = () => <div children={children}/>

    I think there are 2 ways to render children in parent component. I wonder their differences.

    3 Comments
    2024/05/16
    08:47 UTC

    2

    Deploying a vite react app on a VM

    I built a react app using vite and I now want to build and deploy it on a VM. When I tried to look up how to do this I only found tutorials on how I can deploy it on vercel, github pages or other services. Is there a way I can deploy this app without using those services, on a vm locally?

    2 Comments
    2024/05/16
    08:44 UTC

    2

    Object value

    Hey everyone, I have a test and a slice which initial state has a property called hasError which default value is false, and a reducer that just changes that value to true.

    But I don’t understand why the value is false after the dispatch, is it because of destructuring the object only once ? It is not supposed that destructured value is by reference ?

    It(“test”, async()=> {

    const {mySlice: { hasError } = store.getState();

    console.log(hasError) // false (as initial state) Await store.dispatch(setErrorAsTrue()); console.log(hasError) // still false

    }

    But:

    It(“test”, async()=> {

    console.log(store.getState().mySlice.hasError)
    // false (as initial state)

    Await store.dispatch(setErrorAsTrue());

    console.log(store.getState().mySlice.hasError)
    // now it is true

    }

    1 Comment
    2024/05/16
    08:28 UTC

    5

    Visualize React.js Server Actions Flow: an honest attempt at explaining server actions to components flow

    0 Comments
    2024/05/16
    06:58 UTC

    1

    What is your choice on chart lbarary, SVG vs Canvas

    Some people need the chart implemented with svg, Others require chart to be made of canvas. why is there different opinion?? please share your insight

    View Poll

    1 Comment
    2024/05/16
    06:24 UTC

    1

    Max's NextJs course worthwhile after completing React?

    Has anyone done Maximilian Schwarzmüller's updated NextJS course?

    I have completed his React course where he includes about a 3-4 hour section on the App Router. I am not interested in learning more about the Page's Router.

    I see his Next Course has been recently updated. Some older reviews say that the content is out of date and covers Next 13 mostly.

    From Udemy I can see there is at least another 4 hour section about the App Router, but I don't know if this just covers the same content as his React course. There is about an 8 hour React refresher which I am also not interested in.

    I only really want the course if there is enough additional content specifically on the App Router, but I can't find enough info just from Udemy directly or reviews. You can't order reviews by most recent, there's no Q&A section so here I am.

    1 Comment
    2024/05/16
    05:14 UTC

    13

    Best way to start a new React project right now

    Our current setup

    1. Vite with custom npm packages added on need basis

    I am thinking about

    1. NextJS
    2. Remix + react-router + tanstack

    My requirements

    1. We deploy to Google Cloud using managed services like the Load balancer acting as server and Cloud storage to store static build. Ready to spin up Google Cloud run as well.
    2. Mostly Client side rendering
    3. SSR / SSG for landing pages only
    4. Need to separate environment variables from the build (Pain in the ass while keeping static build on Cloud storage bucket, Their change usually requires rebuild, I have separated them out using a /env endpoint in my BFF, Would like to have something that has better support for this)

    Anything else I should look at?

    13 Comments
    2024/05/16
    04:03 UTC

    2

    Where should I put a large json file that my web app depends on?

    Hi folks, I am building an nextjs app which has a map component and it renders a geojson layer on the base map. The geojson file is pretty big (5MB)

    Currently I simply wrapped the json content as a JavaScript variable. As you can imagine, bundle size for the map component is 5MB+. This is obviously not ideal. Not only it makes the website slow to load; it also significantly increases the bandwidth consumption because each time a user loads the page, it downloads 5MB from next js server. Over time, it could lead to unnecessary host cost.

    I would like some tips around how I can best serve this geojson file. I have only some general ideas and really struggle because my lack of experience in web development:

    • put the geojson file in ‘public’ folder as static asset. However I think this doesn’t make much difference because it would still need to be downloaded from nextjs server.
    • use SWR or useEffect() to load the file from S3 when the website is loaded. I am just afraid that downloading 4MB from S3 would significantly slow down the loading process. Should I be concerned?
    • Put it in ‘public’ and use some sort of CDN solution. I never used CDN myself, my concern is that it might be expensive if my site is maliciously loaded by a bot and needs to fetch from CDN too often.

    Could anyone shed some light which direction I should pursue?

    Thanks.

    Update: following a comment, I would like to share more context around what this geojson is for:

    “Basically I have a button “show county layer on map” - once the user clicks it, it displays all the counties on the map so user can click individual polygons(counties) to explore them.

    My current design/thought is to load the geojson data at the beginning when the site is loaded. But I have also thought about not letting it block the other parts of the website (because user most likely won’t go straight to click the display county button), and let it download in the background - I just don’t know how that can be implemented in React, do you know?

    Regarding if I can split the data into chunks - Yes! I can split them. Are you suggesting downloading them in smaller chunks? What’s the benefit of it in this context?”

    6 Comments
    2024/05/16
    03:21 UTC

    4

    Wedding RSVP Mobile Website

    Hey folks,

    Might be the wrong sub but I wanted to build my own wedding rsvp site for my wedding. What's the best tech stack to use nowadays?

    Also wanted to use this as an opportunity to write a flask app but might be the best use case. lmk what ya'll think!

    12 Comments
    2024/05/16
    00:56 UTC

    5

    I created some free nextjs neobrutalism styled templates you can use for your next project!

    1 Comment
    2024/05/16
    00:16 UTC

    2

    Table-like grid

    I'm trying to create a table-like grid that can give me the following sort of look:

    [empty] 1 2 [empty]

    3 [empty] [empty] 4

    [empty] 5 6 [empty]

    except I have run into a big issue. The first thing I turned to, mui's reactgrid, but that was a struggle that resulted in no success. I'm now just really confused on what I can use to do this. Anyone got any tips?

    2 Comments
    2024/05/15
    23:35 UTC

    1

    Confused about how JavaScript accesses the event object and passes it through.

    The browser itself if keeping track of the event objects right? I'm trying to understand how it is working internally and in depth because the actual workings of this concept is kinda confusing me.

    My confusion revolves around how JavaScript interacts with the browser and it's event objects with a single line of code- (blank).addEventListener('click', ()=>{})

    So I get that the event listeners are a function, but how is that function working? We are referencing the element that we want to add the event listener to, so javascript is able to go into the browser web engine, access the DOM and html elements. Since HTML and CSS are not actual programming languages and are simply markup languages, I think I understand how JavaScript is able to interact with it. The markup language has "elements" and the definitions are coded and stored in it's memory right? For example- the <li> tag is associated with the list element, somewhere in the memory. Each character/letter in the code can be understood by the cpu, it understands <blank> is the attempt by the programmer to initialize a element, it gets what is between those elements and it accesses what it means and how to display it... right?

    The bridge is the DOM, which is essentially just a written representation of the visual element that is the website. We see the background color as red, but the DOM sees it as background-color:red. And javascript when it interacts with the DOM sees that this is an object, and it has the ability to update and manipulate objects, that is the core functionality of programming languages like javascript. HTML and CSS however see it differently, more visually in a way, it sees - background-color:red and css has a defined value of what red is in visual terms. The concept of how computers are able to deal with videos and pictures are still hazy to me but fascinating.

    Okay that is my understanding of how JS and the DOM works, correct me if I am wrong PLEASE. Now back to the event stuff. So event itself is just an object like event:(event). It is created to store the details of the event because this is necessary to make websites dynamic, without the event object, a lot of the dynamic functionalities we see in websites would not exist.

    So now the hazy part- How is the event being stored. Is it continuously keeping track of every element in the HTML, and storing every change in memory somewhere? No right? That is extremely inefficient and would slow down the program a lot. So does it only keep track if there has been a specified eventListener that has been initialized? The webpage has multiple elements, you have input elements but also stuff like just normal header elements (<h1></h1>) now, it doesnt make sense for the DOM to keep track of onClick events for the header right if the header is static, same goes really for anything on the webpage that is static, and has no click features of stuff like that. Even on the input, for example, if I just for some odd reason decided to put an input element, but I did nothing with it, no interactions/ dynamic functionality, does the DOM keep track of the events related to it like onChange?

    So is it that whenever I initialize a eventListener in javascript, is it like the DOM itself almost has a listener function also or how does this work? Which listens for whenever I add and eventListener. So whenever it does find an eventlistener that has been initialized, THEN does it start to keep track of the event and store it?

    My main confusion is how the fck does the DOM pass the event object to the eventListener? Where is the DOM object being stored in javascript and how is the function able to access it- .addEventListener("click", myFunction()=>{})? So I asked AI and they said event is not directly pushed to the function as a argument, so then... WHERE TF DOES IT STORE IT.

    17 Comments
    2024/05/15
    22:14 UTC

    Back To Top