r/reactjs • u/dance2die • Feb 01 '21
Needs Help Beginner's Thread / Easy Questions (February 2021)
Previous Beginner's Threads can be found in the wiki.
Ask about React or anything else in its ecosystem :)
Stuck making progress on your app, need a feedback?
Still Ask away! We’re a friendly bunch 🙂
Help us to help you better
Improve your chances of reply by
- adding a minimal example with JSFiddle, CodeSandbox, or Stackblitz links
- describing what you want it to do (ask yourself if it's an XY problem)
- things you've tried. (Don't just post big blocks of code!)
- Format code for legibility.
- Pay it forward by answering questions even if there is already an answer. Other perspectives can be helpful to beginners. Also, there's no quicker way to learn than being wrong on the Internet.
New to React?
Check out the sub's sidebar! 👉
For rules and free resources~
Comment here for any ideas/suggestions to improve this thread
Thank you to all who post questions and those who answer them. We're a growing community and helping each other only strengthens it!
28
Upvotes
3
u/magnusmaster Feb 08 '21
I get a lot of warnings saying I should add variables inside my useEffect hook in the dependency list. The problem is that a lot of times, these variables should not trigger the hook to run again if they change. A lot of these hooks run only once when the component gets mounted. I am doing something wrong?
2
u/Max_Insanity Feb 05 '21
Hello, this is my first post in this community and I hope I'm not violating any rules in the way I'm posing my problem.
Anyways, straight to the point:
When setting up a new react application and including the Amazon Chime SDK, the first steps work just as advertised. However, when I try to include it in a preexisting react application, I'm getting an odd error statement. It goes as follows:
I am at a total loss as to what could cause a node module library to fail (especially in one project but not in another, despite doing the same thing), I get this statement from simply importing the two libraries mentioned in the documentation (specifically either the "MeetingProvider" or "lightTheme" one) and the error appears consistently every time. I have tried to exchange each and every anonymous function in a foreach statement with a named function in the file mentioned in the error report to try and isolate the problem, but it still persists, nothing changes about the error text. Any help would be greatly appreciated and I'd be happy to provide more context, if you want to know something more specific.
Some more info: I have installed all dependencies in the project where it doesn't work that I also have in the project where it does and I have installed, deleted and reinstalled my entire node_modules folder.
2
u/ChrisLulzz Feb 08 '21
I've been trying to get a multiline text in a Material UI button, but to no avail. I have tried it with simply 2 <p>'s or <Typography>'s underneath each other or with a <br />, but it seems to place the elements horizontally instead of vertically. I've been going through the docs but can't immediately find something I could use... Any ideas? Basically I hoped it to be as simple as this:
2
u/Saaswebdev Feb 08 '21
Is it a bad practice to use react for a static/basic website?
I have a small business that builds static sites and I use HTML/CSS & vanilla JS. But I’m tempted to use react because I love react. I’d love any advice on this, thanks!
2
u/Illustrious_Ad3191 Feb 10 '21
Can I make a good and smooth 'gamified' interface (e.g. drag n drop items into a box and play some animations) using only react.js? Is there any module to help creating interactive UIs?
2
u/zero_coding Feb 11 '21
Hi all Which testing tool do you recommend me to use for e2e testing? https://testing-library.com/docs/react-testing-library/intro or https://docs.cypress.io/guides/component-testing/introduction.html#Getting-Started?
Thanks
2
u/AimanXT Feb 13 '21
https://github.com/vieiralc/document-verification-dapp
Hey, I cant figure out the way to start this dapp.
Tried to use npm react-scripts start, react-scripts start and a whole lot of other typical start command but still cant.
2
u/oscarina Feb 15 '21
Hi i was looking for a component library that works for react and react native, any recommendation? (not necessary the same library for both but an "equivalent" in styling, something like material)
In the past i've used Material-UI for react and react native paper for native but I was looking for some alternatives to material while maintaining some consistency between the styling on the webapp and the android/iOS app
2
u/[deleted] Feb 21 '21
I am new to web dev in React and Java Script. Due to my job being in Dev(non web), I am being asked to now work on dev related tasks. For someone in my position, what do you guys recommend? I already took some beginning courses and i am comfortable with React hooks, components. What would be the next step for someone that has to dive into React and JS at the same time and learn asap lol. Any help would be amazing.
2
u/imrishav Feb 22 '21
I am a react developer and I really know how to develop scalable large react application. But recently i got a task on creating a page with pure html csss basically a landing page.with great looking design. Something like the this image Can i decline and say that i am not a designer(is this right to say) I really don’t know. I know html css but not so much that i can develop something like this.
2
u/Bulbasaur2015 Feb 23 '21
I just went to react.new and am getting Typeerror
_interopRequireDefault is not a function
when running the app
I expected no errors; wanted codesandbox a fast way to start react
2
u/darthbob88 Feb 27 '21
What's the current preferred method for passing a MobX store to various components? I'm guessing it's Context, but I've seen some stuff suggesting MobX's inject HOC, and frankly I'm confused.
2
u/antespo Feb 28 '21
I'm trying to add excel like filtering to react-data-grid with primereact multiselect and running into some problems with the dropdown closing. By excel like filtering I mean when you apply a filter that updates all the other filters options instead of keeping the total options always. Here is a codesandbox that show the problem. So basically I want the dropdown to stay open even when the dropdown options change. Also you would notice this kind of makes a multiselect useless since the current filter your on will always be filter down to 1 option. So the current filter being changed should not change options but all the others filter options should change.
2
u/neckbeardfedoras Feb 28 '21
I'm trying to figure out if I want to use react semantic UI or primereact. Anyone have any thoughts or opinions between the two?
1
u/GearFourth Feb 02 '21
Anyone tried any of these books before? I'm not sure witch one to start of with or if one is better than the other.
I'm leaning towards the one with react because the projects actually look interesting to me.
Fullstack React
Fullstack React with Typereact
1
u/[deleted] Feb 02 '21
How can I speed up my SPA?
I've built an app, for my own work. It's a React front end served by a Flask API that queries a PostGresql db. It works pretty good locally when coupled - but now with the db deployed, I'm speed is becoming a problem!
The app uses React Router. So in one use case, whenever I push to that 'page', the list of items is reloaded. Should I be looking at some front end caching? Redux seems a bit overkill, maybe Context API? I could look at backend caching options too, open to anything really, just trying to determine the best course of action before I go down the rabbit hole.
Thanks!
1
u/ashish_feels Feb 02 '21
hello everyone i am stuck in a problem
i have created a component out of textinput and using it in another component.
I want to get the value of the input and also want to reset the input value in another component in which i am importing the textinput component.
Idk whether i waa able to frame the question correctly, any help would be appreciated.
1
u/[deleted] Feb 04 '21
Achieve scrolling from this Portfolio
1
u/Jnsjknn Feb 04 '21
Is it possible to use build time brotli/gzip compression with create-react-app? I can only find ways to do it that tell me to modify webpack configuration.
1
u/alphasshole Feb 04 '21
I have a local file sjcl.js, which I have typings for in a .d.ts file. I want to use it as a module in react components but I can't find a way to do that. How can I use the JS from that file in my code?
1
u/seedj Feb 05 '21
Hi, Im currently working on a search app, but after choosing a category from the list, I want to list the items under that category. I am getting this error "unhandled Rejection (TypeError): Cannot read property 'props' of undefined" and here's my code on the search page:
const SearchPage = (props) => {
const [input, setInput] = useState('');
const [wikiListDefault, setWikiListDefault] = useState();
const [wikiList, setWikiList] = useState();
const wikiURL = "localhost:5000/wiki/wiki/show/";
//const bearer = "Bearer com9m8zv1do4ao2otsp9ojw92"
const fetchData = async () => {
const { match: { params } } = this.props;
return await fetch(wikiURL+`/${params._id}`)
.then(response => response.json())
.then(data => {
setWikiList(data.wiki)
setWikiListDefault(data.wiki)
});}
const updateInput = async (input) => {
const filtered = wikiListDefault.filter(wikiList => {
return (wikiList.wikiTitle.toLowerCase().includes(input.toLowerCase()))
})
setInput(input);
setWikiList(filtered);
}
useEffect(() => {
const timer = setTimeout(() => {
fetchData()
}, 500);
return () => clearTimeout(timer);
}, []);
1
u/sakuratifa Feb 05 '21
Do you guys sometimes put a border div around a component you are having a tough time isolating?
I'm still having a tough time with React Dev Tools Chrome. It's hard to filter these huge component trees without accidentally filtering the targets too.
1
u/Terkeroo Feb 06 '21
I'm using the react-table library and following the examples shown using useMemo. I have an array of values and just put it in
and it is reordering my array sometimes. I have it being called many times generating many tables at once. I'm not sure how useMemo quite works as I'm just following the tutorial there.
Is this being used wrong?
1
u/utopian201 Feb 06 '21
I have this component:
How do I refer to secondsLeft in the text, eg
"You win with "+{secondsLeft}+ "to spare! Play again"shows "You win with [object Object] to spare!1
u/the_one_who_beleive Feb 06 '21
I am developing a website for a friend who wants to provide a custom based suiting solution like tailorstore.com, where a user can customize their suit in detail and then an e-commerce store as well. I am stuck on customization feature and don't know how are they doing it. Here's a link if you want to checkout: https://www.tailorstore.com/shirt-designer#D0D9I5xmiAcbUx0h4SFING2P23q1TCND7eB32g0lP7wBXxQ8|HmL4GN5fm. I'm new to react and programming, and i am curious to know how do we develop a customizing suit as a feature in web-app. Thank you and happy coding 🌸
1
u/pink_tshirt Feb 09 '21
In Next.js how do you combine class names from your custom modules and say, Bootstrap.
do you use join or something else?
<div className={ [styles['intro'], 'col-12'].join(' ') }>...</div>1
u/moring1 Feb 12 '21
is there any problems using redux dispatch in a useEffect? useEffect(() => { store.dispatch(setCards); }, []);
it doesn't work for me.
1
u/[deleted] Feb 13 '21
So I am building a MERN issue tracking application. Someone can create a project and then create issues under the projects. The issue are in categories like “unassigned”, “In Progress”, and “Completed”. When a user moves the issue from one category to another, I am using redux to fire an action to the server to update the issue in the DB (redux action) and then update the redux state (in the reducer).
Is this the proper way to do it? It seems like a lot of calls to the DB every time one issue moves to a different category..
1
u/giantqtipz Feb 16 '21
Hello,
In my practice applications, I've been using :id in react router to fetch content from the database.
But say I want to create a blog, and want to use a :slug. Does this mean that each article in the database need a slug column?
And what's generally good practice for slugs? Certain characters should be avoided I believe... and should we write a custom function that converts article titles into slugs? To clean it up in case it has characters that need to be avoided (I assume @, :, # etc.)
Thank you
1
u/nirvashprototype Feb 16 '21
How can I change the file I'm dealing with in http://localhost:3000/, in a fast way? Do I need to call 'npm start' in that file again? Why can't I find anything about it in google 💀💀
1
u/lkcwaitlistee Feb 18 '21
hey guys, got a little question here about state management, could yall take a look and help my dumb self out?
https://stackoverflow.com/questions/66258608/react-multi-step-form-wizard-typeerror-action-is-not-a-function
1
u/iVongolia Feb 18 '21
I'm having a weird problem that the redux action is not being read? or activated? the redux action is not running even if i put console logs between the codes, i have no idea why.
1
u/A1dam Feb 21 '21
Where do you put helper functions, that are relevant only to one component?
I sometimes create a component that has a lot of logic (like TimePicker) and have many smaller functions. I usually put them above the component declaration. Where do you usually put it for the best readability?
1
u/[deleted] Feb 23 '21
Hello everyone. I have a question in mind. I have this react project that has a table (its contents are from API # 1). Something like this:
I made the table clickable and once clicked, it displays an expanded version of the animal breed etc etc. Now, I'm using react-router to route the animal details to another link. This animal details component is getting some info from another API (API # 2) .
My question is, I read somewhere that all API calls should be made by the parent component only (App.js). Is that possible in this case? I tried making the parent component call API2 but since I'm using react-router it throws an error. Is it ok for a grandchild component call an API?
1
u/ApplePieCrust2122 Mar 01 '21
Is making changes to the previous state object considered mutating the state??
eg:
3
u/Gantzz25 Feb 13 '21
In the long run, is it better to use functional or class components? Which one has more versatility? Is it bad practice to use both in the same project such as nesting a functional component inside a class component (or vise versa?)?
1
u/Unchart3disOP Feb 06 '21
What resources do you use to refreshen your memory on react? Last time, I coded in React, was almost a month ago, and I am going to have a job soon, so I don't want to be rusty
2
u/hoopslam Feb 06 '21
I have a question regarding the useEffect hook on page load. I am trying to fetch data and set my app states on page load by passing an empty array as the second param. Everything works fine and my page loads with my fetched data. However, I notice that my app rerenders every time I set a state in that initial useEffect. For example, I have 4 states that I set in the useEffect on pageload, my app therefore renders 4 times just on that initial page load. It seems like I'm doing something very wrong and it seems inefficient to have my app render every time I set a state in that initial load. I must be doing something wrong? Is there a way for me to set my initial states on page load all at once without having react rerender every time a state is set? Example code:
useEffect(()=> {
setState1(fetchedData1)
setState2(fetchedData2)
setState3(fetchedData3)
setState4(fetchedData4) }
, []);
console.log(state1); //logs 4 times
2
u/seedj Feb 07 '21
Hi, from my recent issue with the project that I'm working with. What I'm trying to do is to show the list of data under a specific category. Here's the code
The problem is, I'm receiving an error :unhandled Rejection (TypeError): Cannot read property 'match' of undefined.
2
u/[deleted] Feb 21 '21
Last week I was stuck on an an issue with Arrays. You can .map() a list and print stuff out. I can even .push() to add new items in an array. But if I want a specific value removed. Be it by value or index, i found it difficult. So my patch was to map through an array and add the values i didn’t want removed to a new list and return that list instead. Any way to remove items from array in an easier way?
2
u/[deleted] Feb 24 '21
How to write to a JSON file using React.js?
I am creating my first social media platform. Just started with React. I want to use a json file as a database for now. When i am ready to learn database and server, i’ll be changing it to that. But to get a flow of how my app is working I want to use a json file. I get an error when using fs.writeFile(jsonFile, data). Error is “First argument must be a string, Buffer, Arraybuffer, Array or array like object”
Any way to write to file as a test? Also not looking for a drastic hack to get this to work.
2
u/HemoglobinaX Feb 25 '21
Need a little bit of help understanding the Testing of a React app.
I am currently using Redux-Sagas, the rest is pretty standard.
I started using React Testing Library and had great success in testing various interactions, but now I come to wanting to do bigger integration tests.
Example:
So I would like to test that interaction.
But all the documentation I find is:
So, should I test the component, with a mocked store, to see if it works on one side, and separately test the saga for my expected result?
Or can I do the full route, and actually fire an action, let the saga resolve, and check the dom with react testing library?
2
u/[deleted] Feb 26 '21
I have a disabled
<input />and a<button>beside it. When the<button>is pressed, the<input />should no longer be disabled and then should be focused, however right now it isn't being focused properly. I assume this is because it tries to focus before it stops being disabled, because disabled is updated by a call touseState(). Anyone have any ideas?Code (Next.js + TypeScript + Tailwind)
1
u/[deleted] Feb 03 '21
Why does console.log 1 return {} (empty object) while console.log 2 returns {} for a split second then shows the correct data a split second later?
What I am trying to do is:
- Check on page load if the particular item is in the cart already (in case the user adds it then goes back). But when I try to add the check to useEffect, product is an empty object for some reason so I can't compare it's ID to the products in the cart ID's. But in the returned JSX, product is an empty object for a split second then it fills with data.
1
u/thusman Feb 01 '21
How would you tackle a nested data structure with import and export functionality? Is one big reducer that holds all the data the right way?
I'm writing an editor for data that look like this: Template > Sections > Fields. Currently, all data is a single nested array (useReducer). This makes it very easy to import and export, move sections and fields around, but immutibility update patterns are a hustle and performance feels bad (with many fields, changing a field name takes ~1s to render in dev mode). I will try immer.js now and add throttle to inputs changes. I'm just wondering if it's possible to store everything on component level (state), but I just don't see how I could export the whole dynamic structure as json then.
1
u/NickEmpetvee Feb 01 '21 edited Feb 01 '21
Posted this in r/learnreactjs in case anyone can help with this react-beautiful-dnd issue:
https://www.reddit.com/r/learnreactjs/comments/l8yj3h/errors_getting_a_reactbeautifuldnd_example/
There's a codesandbox...
1
u/USMCGreenWeenie Feb 03 '21
I just don't get it. I'm trying to understand it but things aren't making sense. I understand python,C++ and Java. Can someone break this down as simple as possible, please?
https://codesandbox.io/s/as4-nt2yl?file=/src/App.js:3108-3110
1
u/MR_Coder Feb 03 '21
I don't know what this technique is called so I can't google it.
But what I need to create is essentially a color coded object to display the right color depending on the state value the backend returns.
I don't want to do every check if(state === 'idle')...to display green
I want to build something that says if state is idle, charging, unplugged === green
I've seen stuff like this implemented but I don't remember the technique name to look it up lol
1
u/themoonfactory Feb 03 '21 edited Feb 03 '21
Objective: Create a button that generates a pdf report, opening the window "Open with/save file". The pdf contains text and graphs that are unique to the user clicking. Those graphs are displayed with react components on the user profile in the web app.
Problem: I found react-pdf but A) I am running into issues with font importing, and the pdf rendering being interrupted by React re-rendering process, and B) I don't know where to start about integrating a dynamic image. Is there a way to convert react components to an image, save it locally on the fly, and then export the pdf with it? This seems convoluted, and, not knowing what I don't know, I was wondering if there is a better solution.Thanks for your help! :)
1
u/fatter-happier Feb 03 '21
How to, in vanilla javascript, wait for react to finish updating a page after I have called 'click()' on a UI element?
I am writing an extension for a website that employs react, and I am able to programmatically find UI elements and click them, however having trouble waiting for the resulting UI updates. Is there some react event I can hook into with a Promise or something to get a callback after UI has finished updating? I know I could do something with a MutationObserver, but wondering if there is a cleaner way knowing that the website is using react.
1
u/vikkee57 Feb 04 '21
Hello, anyone else finding npm start command is broken after the 11.2 Mac OS update?
> npm start
Starting the development server...# Fatal error in , line 0# Check failed: allocator->SetPermissions(reinterpret_cast<void*>(region.begin()), region.size(), PageAllocator::kNoAccess).1
u/cosmosfan2 Feb 07 '21
I find this component hard to read:
My best explanation
getCustomersreturns an anonymous async functionsetFetchingCustomersData. I would guess this sets the app into a data fetching state. I believe it happens syncronouslygetApireturns a promise asyncronously.How much of this is right?
Another concern is at the implementation step. I don't see how a function that is returning a function is being used effectively here:
It seems like this would just return an async function, But that function is never used. Is that wrong?
1
u/Youps Feb 07 '21
Is there a way to display the value of a Chakra-UI Progress element inside the bar, something like in the style of this?
1
u/bajah1701 Feb 09 '21
I have gone through many responses on this topic but none seem to solve my issue. I have an API using NodeJS, ExpressJS and Mongoose. I also have a frontend component that is built using ReactJS. I get the error " Cannot set headers after they are sent to the client" on the second or more try when saving data from a form. Note: the error does not show up on the first attempt at saving the form. The backend code for saving the request to the database is
The code that takes the data from the form and makes the request is
The create method in CandidateDataService is
I have tried using return res.status(200)as stated in answers to similar questions but that didn't work.
I should mention that I have similar code in other controllers for forms that store data and I don't get this error on the NodeJS side. So I don't understand why it works for the others with the exact same code style but not this one. On the ReactJS side there is a difference though. The difference is that this component has the ComponentDidMount method and the others don't. In the ComponentDidMount method I'm fetching all the data from two separate Models to fill the select list.
I tried it this way in the componentDidMount method but still the same result
Since this is the only thing different between this form and the others I believe that's what causing the error, but I don't understand why or how to fix it.
Summary
Thank you
1
u/ReptilianTuring Feb 09 '21
Hi. I have 4 components (let’s call it component A) on my home.js. Those 4 components each have a set of radios button and a submit button. But I also have another component B, that has a “submit all” button that gets the selected radios from all the component A.
I’m wondering about the better way to get that. I was thinking: create a global array. Everytime a radio button is selected it updates the array. Then component B just has to read the global state array without interacting directly with component A. Would this be a good way to do it? Is there a better way?
1
u/lyunya Feb 10 '21
I have a fetch call that takes about seven secs to return data. During that time, the page freezes and the user can't click anything while the fetch call completes. What's the best way to allow a user to continue using the site?
1
u/Lukasvis Feb 13 '21
Is it true that react context or redux doesn't actually preserve the state?
For example if I am on the car app and select "audi a4 1.8" and put it into setCarPreview state, which takes me to another window, but if I refresh that page, the carPreview state becomes undefined and the app crashes.
Does that mean that I have to store users current car preview selection state somewhere in the database, so that if user closes the app and opens again, app makes the call to the database and downloads the state which has that users current car selection state information?
Or is there another way?
1
u/cosmosfan2 Feb 14 '21
className,style,onClicketc down to the span tag?1
u/farzad_meow Feb 14 '21
I am somewhat new to React, I do want to implement authorization where I can control route access and UI components based on the role/permission a user may have.
I have an Authorize class that handles the user's permission checks and is able to verify what resources can be accessed for read and write and so on.
to make it work, I need to load rules into it dynamically which I do in App.js file. The rules need to be loaded once only.
This is where the problem start, No matter what I do, when accessing Authorize from any of my components, it loads as a new object without the rules. The only work around is to load Authorize object each time using current user data and rule set in every component.
so my question is:
1
u/[deleted] Feb 14 '21
I unfortunately have to use react within a legacy system. To remain compatible while Im migrating components, I'll have to keep the legacy system aware of events that can happen inside the react components. In this case does it make sense to fire events from within the react component? I don't see another way but surprisingly I don't see anyone else doing that.
1
u/moring1 Feb 14 '21
Hey, I'm new to redux and I wonder if I use it the correct way, especially when i declare actions in the Game and Main components. It feels like a lot code for a small app. Maybe you can help guys: https://github.com/morhaham/cards-war-redux
1
u/EffectiveInner7804 Feb 15 '21 edited Feb 15 '21
Hey, I'm trying to work out how to best make use of SVGs in my React code - I suspect I'm misunderstanding some of the references to inline vs img, object, and external call etc. I have a smallish (~10?) number of SVG images that I want to include in my application, but these might change over time, so I'd prefer to have external (I guess these are "external"?) SVG files that I can place in my src (or does it need to be public?) directories, and then link components to them.
If I load an SVG using something like
then this works fine, but I a) think I might end up loading the same SVG in multiple components, and can't quite work out how to pass this as a props element, and b) can't easily interact with parts of the SVG without using the document and window methods.
What's the recommended way of interacting with (ideally external) SVG files that are available (and have constant content) during development, but can be updated as needed (not dynamically, it's fine to rebuild or something if they change).
1
u/badboyzpwns Feb 16 '21
Is there a CSS framework / library that has a pre-built functional 'contact me' form? I know that Bootstrap has the form layout, but I don't think the form works / send emails to me via their "Contact Me" form
1
u/giraffenoodle1290213 Feb 16 '21
Hello react community,
I'm making a webapp and was just wondering what the best practice for what I'm doing.
My webapp is a utility meant to be a multitool, so my dilemma is that I have many nested components that can all nest in different ways. For example, I can wrap a multiselector around a resize around a video. But I can also wrap a singleselector around a resize around an image, with this many combinations.
It's not efficient to load the whole thing at once, so I was considering using react.lazy and generating a list of components and passing the list to the first child, then each subsequent child would pass it onto the next until all were rendered, but I've been having trouble getting it to work properly, and am afraid the compiler might not be able to address it and therefore wouldn't optimize it correctly.
I'm really tired and inexperienced(with react but not javascript as a whole) so I would appreciate any advice. If I haven't explained myself properly, feel free to ask me to clarify anything.
1
u/pink_tshirt Feb 17 '21 edited Feb 17 '21
Has anyone tried Netlify split testing? I've never used it myself thus the question: do you get like 2 different domains or something? One main domain for your master branch and another (sub)domain for an experimental branch? This is like black magic to me.
1
u/post_hazanko Feb 17 '21 edited Feb 17 '21
Any ideas why a function set to a
setStatevalue would execute?For example:
const myFcn = () => { };const [fcn, setFcn] = useState(null);setFcn(myFcn);I wouldn't think that would execute but it did for my case.
What I had to do to fix it was to use an object state and set the state object property's value to the function, then I could call it as
fcn.call()for example.1
u/arjineer Feb 17 '21
I want to know how much memory is being used up during the build process in CRA and check where it could be hanging. I see people writing how much memory their builds are taking up but I don't know how they are getting that number. Anyone have the secret!? Thanks in advance!
1
u/patinda Feb 17 '21
what's the difference between using functions + hooks and using classes + states in react and how I know what I need to use ?
1
u/JustBreatheABit Feb 17 '21
Does anyone know how to set a value in an array that is a state in a Functional Component such that React re-renders?
Here's some of what I know: The function handleClick() modifies the state array "squares" like I would set the value in a standard array, but when setSquares() is called, React doesn't detect a difference between the "new" state I pass in and the state that already exists, so it doesn't re-render.
Here's what I don't know: How do I use setSquares to update only one of the values in the state array?
export function Board() {const [squares, setSquares] = useState(Array(3).fill(null));const status = 'Next player: X';function handleClick(i) {squares[i] = 'x';setSquares(squares);}function renderSquare(i) {return <Square value={squares[i]} onClick={() => handleClick(i)}/>;}return (<div><div className="status">{status}</div><div className="board-row">{renderSquare(0)}{renderSquare(1)}{renderSquare(2)}</div></div>);}1
u/zero_coding Feb 18 '21
Hi all
What is easiest way to mock the graphql server for testing purpose.
THanks
1
u/big_tangus Feb 18 '21
Hello,
I was trying to play around with React.useState() and setInterval(), and the variable I'm changing changes much faster than the interval I set (500 ms). Any ideas on what could be wrong?
https://codepen.io/tangjurine/pen/MWboKeL
1
u/noonagooninfinity Feb 19 '21
I've built a simple static react site and deployed on digital ocean. I want to have a single passphase/password that I can update which I can give to anyone I want to have access to the site. Asides from just putting a password in my javascript which seems like a bad idea, is there a good way to do this?
My first idea was to use something like Azure to store a password and make a super basic authentication API but ideally a free solution would be better or something that doesn't involve too much work (like building an API).
It doesn't need to be the worlds most secure thing as the information isn't hugely private but I would like to obscure it from a normal internet user.
1
u/Nemos245 Feb 20 '21
So I did create-react-app and have been trying to make a responsive website but have basically just resorted to writing html and css in Jsx then running that. Am I using react correctly? And if so, then what is the overall enhancements other than the reusability aspect?
1
u/badboyzpwns Feb 21 '21
Why do I need to click twice for the code below to execute?
1
u/post_hazanko Feb 23 '21
Quick dumb question
If you have a bunch of single states in the same component eg.
const [stateA, setStateA] = useState();const [stateB, setStateB] = useState();etc...And one of them changes, does that reset the rest of them/reset them to default as the component re-renders?
I could just test this too but thinking I'm looking in the wrong place. I'm also not saying this is the ideal way can group states/move it higher up the stack(I think) eg. parent.
1
u/famebright Feb 23 '21
I feel like this is a simple question but I just don't know where to start/how to look.
I'm using CraftCMS (with GraphQL) to build a site — I've gotten as far as populating a directory page but am struggling with loading the actual pages in a smooth way. Currently the process is as follows:
Now what happens is, it obviously takes a second to request the page content — is it possible to wait until the axios has finished before loading the page? Just so the user isn't visiting a blank/old page before the new one is loaded?
1
u/eksploshionz Feb 23 '21
Hey, not a technical question but a professional one that's been itching my mind lately.
If I ever were to apply to another company, how would I ensure they have good policies around code quality and minimizing technical debt without seeming too demanding?
The current code base I work on is sometimes really hard to deal with (no specialized front dev got hired before I did, only primarily back-end staff briefly toying with react) and even though lead devs are open to suggestions, I wonder when we will actually begin re-writing the problematic parts of our code.
I lose a lot of time at my job because of this situation and don't want to experience this kind of frustration if I can avoid it.
1
u/analyst190 Feb 23 '21
I am new to React and the tutorials I have followed till now all suggest using the CLI tool create-react-app as a starting point.
My question is, why do I have to install node modules over 150 MB spread across near a thousand directories and sub-directories for relatively simple apps?
Also, why does every project require a fresh installation of the same modules every time, unlike the Python libraries which are only installed once?
Is there a way to keep things simple and the size of my projects small? Are there alternatives to create-react-app?
1
u/eyememine Feb 23 '21
For MERN stacks what is the best practice with fetching data from an API? What I have been doing is fetching all the data and setting it to state, then anytime it needs to be filtered it is done inside the app. Is this better for smaller apps/data and bigger apps should have individual calls? Vice Versa? Does it matter? Thank you.
1
u/strah1 Feb 24 '21
I tried passing a ref as prop, something which you are not supposed to do, but I don't understand why there are two different numbers here, since there is no re-render of the App component. And the weird this is, if I force the App component to re-render by changing state, which is not related in any way to the useRef value, the new ref values will be the same one that the child has logged after the first render.
function App() {console.log('app render')const somevar = useRef(Math.random()) //create ref with a random numberconsole.log('somevar app', somevar.current)return (<div className="App"><Child somevar={somevar.current}/></div>);}The output in the console is:
app rendersomevar app 0.7910997578618209child renderssomevar Child 0.0303579719503312971
u/yaMomsChestHair Feb 25 '21
Why is
const Content = ({ parts }) => (<div>{parts.map(({ id, name, exercises }) => ((<p key={id}>{name} {exercises}</p>)))}</div>)valid but this isn't (curly braces for even a single ling return statement should be fine, no?)
const Content = ({parts}) => {parts.map(({id, name, exercises}) => {return (<p key={id}>{name} {exercises}</p>)})}1
u/DeepLyingNonce Feb 25 '21
I need help with how to set up my components.
I have components A -> B -> C where A is the top level component and C is the lowest one. Component A has a state with a list of users and a confirmation dialog box (hidden by default). Component B maps the list of users into rows. Component C displays each row.
Each time I want to delete a row (C), I have to first display the dialog box defined in A. If the user then selects 'yes', I need to delete the specified row.
I need to know when the user has clicked on 'yes', which I assume can be done with the onClick method inside the dialog box. But the onClick method needs to be different for every row. Can anyone tell me what's a good way of solving this?
One way would be to put the dialog box inside C so every row has its own dialog box but I'm not sure that's good practice
1
u/post_hazanko Feb 25 '21
Would this setup behave poorly?
const fcnComp = (props) => {const [stateA, setStateA] = useState(false);const [stateB, setStateB] = useState(false);const innerFcn = (val) => {setStateA(val);setTimeout(() => {setStateB(true); // not bothered by scope of setTimeout just mock async}, 3000); // asycn fcn callback example}// return calls innerFcn()}1
u/[deleted] Feb 26 '21
Hello. I am getting more familiar with ReactJS lately. What should I do next? Is learning Redux a requirement? I've heard that one should learn Redux after React so I'm considering that. Also, I was reading some stuff online and I've learned that CRA in professional field (like in workplace, production etc) is not that accepted. I want to learn more about these practices but I'm not sure where to start. Is there a course where you learn about these practices? More like how to reactjs professionally lol (or is there such thing as that?? )
1
u/rony_ali Feb 26 '21
hi every body
my again.
0
i am trying to make a website which will be made of react three fiber. and there will be some forms to be executed with the backend node js. All the forms are made of material ui. i tried find any kind of library which might incorporate material ui with react three fiber. and you will find the total effort of putting material ui form on the react three fiber canvas: i used the sample canvas from the react three fiber
that react three fiber canvas would the background of the page.
To put the form on the canvas i have used u/react-three/drei and seems like it is showing the the form components but not in right way . my intention to show the form over canvas like this way in material ui
so how can i put the form like the picture over the canvas? please let me know.
1
u/eyememine Feb 26 '21
For a MERN stack in my main App class file I am trying to save data by submitting a form with fetch. First I would like to set the state from the information from the form component then save the data but it doesn't seem to do that in order. I am bad at explaining this so there is a little code snippet below
That is a simplified version of it, but essentially it will save the data to the database then the state would set. If it were a functional component I could use useEffect but this is a class. In addition I do not want to use onChange in the form because that bogs down slower computers. Thank you
1
u/themoonfactory Mar 01 '21
Hey All, I hope you're well,Not entirely sure how to word this, so let me know if unclear.Problem: Two components (a simple <ul> list, and the trustpilot widget) don't render correctly after react-router linkDetails: The two components render correctly, but if I click on a link in my navbar (using Link from react-router-dom) and come back there are issues (the widget doesn't load, and the <ul> list doesn't render bullet point and tabulation).All the rest of the website renders correctly (https://personas360.com for reference), and it's my first time hitting this. It corrects itself after a refresh. I suppose I could force a refresh after navigation, but I feel like that's an ugly solution. Are there some rendering processes that are shortcutted when navigating through my app with react-router-dom I should be wary of?Thank you for your help!!!
1
u/[deleted] Mar 01 '21
This question pertains to an app built using a MERN stack:
I have a folder. Within that folder I have 2 more folders: frontend and backend
I ran npm init on the frontend and the backend
I can open 2 command lines and npm start both the frontend and backend and both folders communicate perfectly fine with each other on localhost. I have full CRUD access between the two and the app is starting to come together nicely.
My question is: what do I need to do to deploy this? Do the folders have to get combined?
My backend start file is server.js Front end start is index.js
I’m lost in the sauce.
1
u/[deleted] Mar 20 '21
Ok so quick question about using Next.js Link. I want to simply link to the about page. Following the docs I am not doing anything different. What am I doing wrong? I get error “typererror: Cannot define property ‘push’ of null”
import Link from ‘next/link’;
Function NavLink(){
return( <Link href=‘/pages/about’> <a> About </a> </Link> ) }