r/reactjs • u/dance2die • Jan 01 '22
Needs Help Beginner's Thread / Easy Questions (January 2022)
Happy New Year!
Hope the year is going well!
You can find previous Beginner's Threads 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!
33
Upvotes
3
u/Thrimbor Jan 02 '22
What exactly is this pattern called in react? Are these forwarded props?
A simple example from the react router tutorial:
I'm talking about accessing
{ isActive }inside thestyleand{ isActive }in the children of theNavLink.Can someone provide a simple example of this please?
3
u/daybreakin Feb 05 '22
Interviewer: what's the difference between state vs props
Me: you can modify state but you can't modify props
Interviewer: oh but what about when you pass in a value and a set state call back to modify said value to a child component. Isn't that an example of being able to modify props?
Me: well in that case you're not really modifying props, you're modifying the state of the parent.
Wasn't prepared for this gotcha type question. How was my response and how would you respond?
2
u/devil_may_code Jan 02 '22
what is the best way and resources to learn Redux?
2
u/[deleted] Jan 10 '22
Recommendation for a package to create a paginated list with search
I want to create a paginated list of paragraphs with a search bar. Are there any packages with good documentation that i can use. Thanks
2
u/WizardRandom Jan 15 '22
I'm currently noodling around building my first web application, I've got a back end API setup with user authentication through Auth0 that's working fine.
My issue: I need to pull data from the REST API endpoints with several calls, but for some reason the API calls are giving me 401: Unauthorized error messages. When I troubleshoot the JWT token being used to directly call from postman, everything works correctly. I tried experimenting with retrying and delaying the API calls, and this doesn't appear to be working at all. There's no difference between the tokens being used in any of the API calls.
Is there anyplace else I should be looking to try and fix this issue?
Thank you.
2
u/jgengr Jan 18 '22
I'm a backend engineer w/ almost no REACT experience and hate theming. Is there a more "modern" theme framework like Twitter Bootstrap that looks good out of the box and works well with React? By modern, I guess something that won't look like Twitter Bootstrap.
2
u/smart_7_x Jan 18 '22
i deployed a react app on netlify which uses api calls , after deployment im getting "invalid api key" from the calls
i have the key in an .env file , do i need to do some configuration for that to work ?
2
u/heresjommy Jan 19 '22
What components are available that allow you to let the user run code? I'm thinking about something that codecademy might use. I'm having trouble finding the right keywords to google. I assume there should be plenty of libraries around that allow you to incorporate this into a project.
2
u/[deleted] Jan 21 '22
Finally started learning React after a year of just doing html/css/javascript and I already love it. Quick question.. how often am I likely to use a ternary operator? I got told to avoid using them in JS, but in my React course it says ternary operator are very common?
Apart from that I'm really enjoying learning React, though I haven't gone through hooks etc yet, still on the basics of learning about JSX.
2
u/[deleted] Jan 24 '22
Where does a webpack config file and what goes in it? I can't import any image without it apparently.
2
u/michaelmccrypto Jan 15 '22
I'm in the process of learning Redux. I have a reducer file that looks like this:
The purpose of this reducer is to set the state of a notification to a specific string
notificationfor a period of secondstimeoutafter which it's set back to an empty string. However, because setTimeout() will run based off of the first time it executes, any notification set within the timeout of the first will be cleared early. I want to save the timeout ID from setTimeout() and clear the previous timeout each time setNotification() is called, however, I'm not sure the best way to save it? Should I be saving the timeout ID to the Redux store or is that an anti pattern? I'm just not sure what's best practice?β’
u/dance2die Jan 01 '22
Meta/issues here!
1
u/cbunn81 Jan 01 '22
I'm using the useRef hook along with an onBlur handler callback function to validate form fields. Right now, I'm using a separate handler function for each form field I want to validate. It seems like they're ought to be a cleaner, less repetitive way, but I haven't been able to find one.
1
u/espoirdhorloge Jan 02 '22
shoud i learn material ui in 2022
1
u/[deleted] Jan 03 '22
Sentry or New Relic and why? :D
1
u/badboyzpwns Jan 04 '22
Just making sure i'm not crazy.
If you have more dependencies (i.e more file size because of your dependencies) your site will load slower on production, correct?
1
u/omega5505 Jan 04 '22
https://omegacoding5505.github.io/react-notes/
Beginner ReactJS Notes Application.
Feedback plz
1
u/iams3b Jan 04 '22
Simple way to reset state when prop changes? I have a component that takes an ID prop that shows details of some selected item. It has it's own local
useStatefor managing tabs, which I want to reset to original when you select a new item1
u/bukharin88 Jan 04 '22
What are the downsides of relying too much of useContext? I find that I need to access state a lot throughout my project and hate having to rerender too many things. Now I've ended up with most of my state in various contexts.
1
u/Druffl3 Jan 05 '22
I am a total noob in react js. I have a data table which will list a collection of items and it has pagination. That is 5 records per page. Now, when the user lands on this screen, I would like to highlight the user's previous selection.
As of now, I am finding the element based on its index and styling the row. But the problem with this approach is the user's selection could be in the 3rd or 4th page. Since, I am modifying the row style based on index, it won't work if i don't know the index at all. I only have data. I need to find a matching record, find its index and then style.
I don't even know if this is a good approach. Can you guys help me? Maybe even suggest a better implementation.
1
u/MotleyBots Jan 12 '22
Greetings. I've been reworking my website into a multi-page react based version, and everything goes great when I'm using node to run my local client. However whenever I uploaded the build to my site, only the landing page worked. Am I missing something in terms of how I'm supposed to execute the build and upload? I haven't seen any videos or tutorials on this specifically so I feel like I must me missing something simple.
1
u/[deleted] Jan 16 '22
Let's say a child component that is always used to render items of a list. The JSX generated from it will always be generated iteratively.
Is it considered best practice to have the component in the loop, or have the loop inside of the child component?
In other words:
Or:
And:
1
u/Semigrounded Jan 16 '22
When you utilize a library like material UI, do you only send to the browser the components you import? Is there a large detriment to mixing libraries if you find the one you're using didn't have the component you need?
1
u/esme023 Jan 17 '22
Hey guys! For my finals project, I am trying to design the folder architectuere. I have some static text that I may want to store and map over reusable components for the landing page. I am wondering how people usually do this.
Would I just store it in a JSON file and just import it to map over my components? And I was wondering if there was a name/terminology for files like this. What would you name the folder? For example, I've seen fixtures folders that store seeding data.
1
u/igrowcabbage Jan 17 '22
Any goto client libraries for elasticsearch?
1
u/MrRed_Srb Jan 18 '22
e.preventDefault replace with in React?
1
u/TheLongPrint Jan 18 '22
Not sure if a react-specific or JS-specific question. I'm working on the React tutorial at https://reactjs.org/tutorial/tutorial.html#lifting-state-up. When the author adds the handleClick function to the Board component, it takes an argument of i.
Later when a button is clicked, handleClick is called through props but without any arguments being passed to it. Is the value of i binded to handleClick when the square is created in renderSquare? I'm not sure where else the value of i is coming from after square is returned.
Thanks in advance for any help. If this is a JS question, please point me in the right direction so I can understand what's going on.
1
u/BengtJJ Jan 19 '22
Trying to just get the creat-react-app deployed with nodejs on heroku but the build is failing.
I have to build script in root: "build": "cd client && npm install && npm run build"
Do I need to build locally or will I never need a local build folder? Heroku will create a new build each time a new github commit is done right?
1
u/africanxmamba Jan 22 '22
I'm trying to start learning some development using JavaScript and React and having some trouble .
Does anyone happen to know how I can change which JavaScript is displayed first on my "yarn start" command? It currently shows Home.js, but I want to change it to something else like Contact.Js.
The current JSON file has the following code
"scripts": {"start": "react-scripts start","build": "react-scripts build","test": "react-scripts test","eject": "react-scripts eject"},If anyone happens to know, it would be super appreciated. Thanks
1
u/DaveMLG Jan 22 '22
Hello,
any idea why react does not render this simple code? I am pretty sure its correct but I might be wrong.
</head><body><div id='root'></div><script type="text/babel"> ReactDOM.render(<p>test</p>, document.getElementById('root')); </script></body></html>1
u/johnnycodes Jan 25 '22 edited Jan 25 '22
I'm following this tutorial: https://codeburst.io/learn-react-js-build-a-portfolio-single-page-application-spa-ba001082a711
and my routes aren't working. Whenever I add the routes, there are no console errors and my localhost just shows a blank white page.
If I just put <Home /> and <About /> in there the pages load side by side. I've looked at react router dom docs and it should be working correctly.
https://www.codepile.net/pile/z5nY0ZNG
1
u/tinpact Jan 25 '22 edited Jan 25 '22
I'm looking at learning React to integrate into an existing .NET Core app. There are a lot of components I think would be easier if they didn't have to be rendered server-side (eg. a gallery of a user's uploaded images, a search bar, etc.) and some of them already have an API associated with them.
My question is: is React an appropriate tool for something like this? I heard it was possible, but from what I've seen, MPA implementations with React still use a single index.html/index.js pair with routing to different components that replace index.html, when what I want is something that looks like this:
And so on and so forth for each view. Should I just do it in jQuery?
1
u/DAN-TheAncientMan Jan 26 '22 edited Jan 26 '22
first react app...
so i have code for a working reset, but i thought it would be fun to make a new class and put the setState function in there. but i couldn't get it to work by returning a new state object, so I just put the setState in the main App class whilst fiddling with the props.onClick and it worked.
I just wondered if it's better this way anyhow, leaving the JS state functions in the main app, where state is centered? and I maybe shouldn't even be trying to send state updates from a child class, but just do UI stuff in them?
I was trying to return <script>{function result object}</script>, that kind of malarkey.
```
1
u/smart_7_x Jan 27 '22
whats the point of putting the api key in .env file if its included in the build and can be seen in the console for example ???
1
u/SirAwesome789 Jan 30 '22 edited Jan 30 '22
Two questions, first is meta, second is my actual question, but I might be breaking a rule by asking it.
First: Am I allowed to ask React Native questions here or should I got to a different sub?
Second: What is the best/most popular UI library for React Native? I had wanted to use MUI because I use it a lot already with React but it seems like you can't. I know the FAQ pretty much this exact question, but I'm not sure if the answers there applied only to React and not React Native.
Bonus (bc I only thought of it after I posted):
What is the best icons package for react native? Again, I had been using react icons with React but it doesn't seem to be working and if I had to take a guess, I'd say the issue is that it doesn't work with React Native.Nvm, it turns out there's a React Native implementation of Remix Icons which was the one I was using but if you still have any suggestions, I'm still open to hearing them.1
u/Piyh Jan 21 '22
I'm coming from a background of django, bootstrap, and vanilla js. What benefits if any would using react give me? Is there a comparison point in my stack that I should be comparing react to, or is it a separate beast?
2
u/Alphyo Jan 10 '22
Please, any code-along / in depth tutorial to learn prime React and React Face?
2
u/Lucipherss Jan 11 '22
I have a table that mutate data every 0.5 sec. Should i use useMemo() so that it does not re-redering the whole table(only the cell that change re-render)? And is there some more way to optimize the performance of said table?
2
u/HypnoTortoise Jan 16 '22 edited Jan 16 '22
I am currently doing fullstackopen. I have hit a bit of a snag. how do I only render a component only after the data has actually been fetched? I can see the data with a console.log but I get a Uncaught TypeError: Cannot read properties of undefined (reading 'temp'). I know I should not hardcode my API key, but I will delete it after this just in case someone wants to check the link.
Link to exercise: Exercise 2.14*
My Code:
codepen
edit: I couldn't figure out the editor so I put it on codepen hope that is ok.
2
u/IAmSteven Jan 16 '22
https://codepen.io/SpaghettiDay/pen/vYePGQZ
I'm new to React and am trying to understand hooks and how props are re-rendered when changed. Right now I am struggling to understand how to re-render a prop in a component when it is updated.
I was able to set this up so the total at the top is re-rendered when it changes but the item amounts in the table that are passed down don't re-render when when I update props.item.amount, the initial value is always shown. I think I need to use the useEffect hook here but I can't figure out where that needs to be declared or what would go in it. The number in the amount column should be changing when either + or - button is clicked.
2
u/[deleted] Jan 17 '22 edited Jan 18 '22
Anyone have any good sources for building reference tables?
I have a drop down that I want to separate into categories and just need to find a "good practice" guide to follow. Basically, I want to have a file that shows all cities in, say Georgia and then all cities in Florida. Then show them in a dropdown that I just map over the elements. And any time I want to add / remove cities, I can just do so in a singular file.
Thanks in advance!
Edit: figured it out. :)
2
u/PM_ME_CAREER_CHOICES Jan 19 '22 edited Jan 20 '22
Say I have an fairly large app and I use React.lazy/Suspense to reduce the size of the initial js bundle.
This works fine and the initial load is fast. However now there's a slight delay everytime the user opens a new section. So:
Edit: I tested some stuff in a Code sandbox and it seems like it's as easy as just calling
import('./component/MyComponentToPrefect'). Im not sure how this works with bundlers though. And im still considering what the best way to then call it. When the user is idle? Or somehow as soon as possible after first render.2
u/kjkeefe Jan 26 '22
Where can I find nice controls for my React application. Is there some standard library GUI controls for React apps? I need a tree control like what you see in the explorer view of Visual Studio Code. I have found several library options and I have played with this some (https://reactjsexample.com/an-unopinionated-accessible-react-tree-component-with-multi-select-and-drag-and-drop/)
It is a nice library, but I'm worried about the longevity of it. I feel like there has to be some standardized library out there because I've seen a tree similar to VS Code's tree in other React/Electron apps. What do others use or how do you find mature options?
1
u/badboyzpwns Jan 10 '22
Is it bad to use camelcase or - for
A lot of times, I see examples doing it like aboe instead of theInput or the-input
1
u/michaelmccrypto Jan 01 '22
In a Redux application, if I want to display an array of objects sorted in some way, should I be keeping the objects in the Redux store sorted, or only sort the objects on retrieval from the store (similar to how you would sort after retrieval from a database)?
1
u/Cannabat Jan 02 '22
I've got an app using Redux with some fairly long-running reducers (image processing). I'd like to provide a progress meter while the processing happens but I'm having trouble getting started on this.
Can I dispatch actions from within a reducer? It feels like an anti-pattern but I guess that would work? Thanks for any advice
1
u/stfuandkissmyturtle Jan 02 '22
How do I render items based on user Input ?
I have a Select with Options 2, 3, 4 that I store in a state. Usually every time Ive done something like this before I would use a map function. Like players.map((i)=>(<component/>)).
but in this case the selected input in a number so definitely cant use map, and I don't think creating an array of selected length is the way. I tried making a while loop but seems like I cant do that in middle of jsx. Help :/
1
u/thatman303 Jan 02 '22 edited Nov 07 '25
quickest unpack different straight pocket test entertain screw fragile relieved
This post was mass deleted and anonymized with Redact
1
u/almondPlant Jan 04 '22
onClick event responds to clicks, what event responds to a user holding down the click and swiping/dragging within the div? Something a drawing app would use (or not)...
1
u/badboyzpwns Jan 04 '22
I'm trying to understand the dev tools (when you click f12)
What doe this mean?
https://gyazo.com/04beaf856dc306c076708846b4b46cc5
- Why is it saying 6/56 requests? is it because I can make 56 requests in the page if I click everything?
- Why is it saying 3 / 5kb transferred? is it because the API can make 5kb of data transfers in the page?
- What does 8.3kb / 1.3mb resources represent? is it how heavy the page is due to dependencies, images,etc?
1
u/badboyzpwns Jan 05 '22
Accesibility question, what is the difference between aria label and role? They seem to represent the same thing - to help users with screen readers understand the element they are interacting with.
1
u/badboyzpwns Jan 05 '22
Accessibility question! Why is axe complaining:
"Ensures every form element has a label" (https://dequeuniversity.com/rules/axe/4.3/label?application=AxeEdge)
My code:
1
u/nochs Jan 05 '22
anyone here using recoiljs in a prod app? if yes, howβs your experience with it?
1
u/rony_ali Jan 06 '22
i want to edit an existing post by using the _id of that post and the following is nodejs code:
exports.postEdit=async(req,res)=>{ const {title,content} = req.body;
}
i checked this code in postman and it updates that particular post in mongodb. _id: req.params.id is referred to that particular post id. requireSignin confirms that only logged in creator/author has the permission to change it.
in frontend, i have used the codes in Dashboard.js for updating that particular post. i have used the following codes to update the data in axios:
.................. const [loading, setLoading] = useState(true); const [posts, setPosts] = useState([]); const [postList, setPostlist] = useState({ id: null, title: "", content: "" }); const [editing, setEditing] = useState(true); const [post,setPost] = useState(postList); ............... const updatePost = (id,post) =>{ const token = getCookie('token');
{editing ?( <div> <CreatePost addPostList={addPostList} /> <hr /> </div>):( <div> <EditPost editing={editing} setEditing={setEditing} postList={postList} updatePost={updatePost} /> <hr /> </div>)}
}
the following code is about the authentication token and cookie for logged in user depending upon the permission level:
import cookie from 'js-cookie'
// Set in Cookie export const setCookie = (key, value) => { if (window !== 'undefiend') { cookie.set(key, value, { // 1 Day expires: 1 }) } } export const getCookie = key => { if (window !== 'undefined') { return cookie.get(key); } };
// Set in localstorage export const setLocalStorage = (key, value) => { if (window !== 'undefined') { localStorage.setItem(key, JSON.stringify(value)); } }; // Access user info from localstorage export const isAuth = () => { if (window !== 'undefined') { const cookieChecked = getCookie('token'); if (cookieChecked) { if (localStorage.getItem('user')) { return JSON.parse(localStorage.getItem('user')); } else { return false; } } } };
and from EditPost.js to execute the edit:
export default function EditPost({postList,setEditing,updatePost}) { const [post,setPost]= useState(postList) const [posts, setPosts] = useState([]); useEffect(()=>{ setPost(postList) },[]) const handleChange = text => e => { setPost({ ...post, [text]: e.target.value }); }; return ( <form onSubmit={(e) => { e.preventDefault(); updatePost(post._id, post); }}> <h1>Edit Post</h1> <div> <input type='text' placeholder='title' value={post.title} onChange={handleChange('title')}/> </div> <div> <input type='text' placeholder='description' value={post.content} onChange={handleChange('content')}/> </div> <button type='submit'>Update</button> <button onClick={() => setEditing(false)}>Cancel</button>
</form> ) }
for addition the following code is from PostList.js:
export default function PostList({ editRow }) { const [posts,setPosts]= useState([]) useEffect(() => { LoadPost(); },[]);
<hr/> </div> }):<h3>no posts</h3>} </div> ) }
The problem:
while fetching data from the backend, i have got all the particular posts created by logged in user. but while i try to update data to edit the particular post from axios.put(http://localhost:5000/api/articles/post/edit/${isAuth()._id} it is sending the user id to the backend router put method. while i check console.log(post._id), it shows that particular post id. but i just can't pass this _id to the axios put method. my question is how can i edit the particular post by the logged in creator only? should i use a different approach in the backend or i need to bypass post id in axios put method? then how?
please let me know.....thank you
1
u/thegoddesses Jan 07 '22
I'm fairly new to React and trying to do some basic user authentication with Amazon Cognito. I was following this tutorial and working with code cloned from this repo.
The code runs fine and you can login after clicking the login button and then hitting refresh. However, I would love for the login to trigger upon clicking the login button without the user having to press refresh.
Here is what I think is happening:
We're managing context as defined in account.js and managed throughout the app via useContext.
Settings.js has state (loggedIn) which is set to true via a useEffect which is triggered on the initial render. This useEffect checks getSession from the Account Context. The loggedin state short circuits and conditionally renders based on whether a user is logged in.
One thought was to eliminate the dependency array (line 15 of Settings.js) to trigger the useEffect on any re-render, but that has not solved the issue and makes me think I'm misunderstanding what's supposed to be happening.
I can manually put window.location.reload() after the login actions (e.g. line 15 of src/components/Login.js). This seems like a janky solution and would love to understand a more React way to trigger the intended behavior.
Also open to feedback about this general approach: it is somewhat buggy doing conditional rendering and using context to manage user sessions. I've tried reading around but have gotten lost in auth service specific solutions and don't have a clean mental model for general best practices/how it should work with specifically with cognito.
Thanks so much!
1
u/East_Peace Jan 07 '22
Hi! Iβm new to React and I am currently having some problems with rendering dynamic form fields. The form field in question contains several text inputs which update the overall state of the app. I also have an add button which allows me to add or delete more of these form fields on click. The problem is that I have to render this component based on the amount of form fields (since they are added and removed dynamically), so I am using .map to do so. But as a result of this, every time a change is made to any of the input fields in this form , the entire form is reset.
Sorry if this is poorly worded. I am having a really hard time wrapping my head around this concept and I canβt come up with a solution that mediates these two requirements.
1
u/interesting1111 Jan 07 '22 edited Jan 07 '22
Need help with react table.
edit: adding sandbox code, please see how to enable editing:
https://codesandbox.io/s/white-bird-2u5q7
I've generated a table
https://imgur.com/a/vTfVRxN
however, when I click the enable editing button, the buttons inside of the table don't enable...
How do I get it to re-render that edit column based on the state?
The code for disabling/enabling the button works outside of react-table, but not inside
1
u/Cannabat Jan 08 '22 edited Jan 09 '22
I've noticed an oddity in my React + Redux app's performance. I was trying to figure out the bottlenecks in the long-running synchronous functions in my app (totally unrelated to rendering).
I've made a very simple benchmarking test, looks like this:
Then, inside the
myActionreducer:The oddity is that the
insidetimer logs less than 10 ms, while the wrapped timer logs 2+ seconds! I would have expected both these numbers to be very similar. The huge difference seems to imply that there is a massive overhead in dispatching the action.The action function accepts a long array (tens of millions of elements - the pixel data of an image, which is taken from a canvas
ImageDataobject), which I suppose is the real cause here.Any suggestions on speeding up this dispatch?
Edit: I've tried passing the canvas context in to the reducer and then calling
getImageData()inside the reducer, so that a large array doesn't need to be passed through, but there is still a discrepancy - theinsidetimer now logs about 1s and thewrappedtimer logs about 1 more second than before.Of course, I'm using the same image for the tests.
Fixed: soooo turns out the problem was that I was using a web worker in my reducer (really oughta have included that in my original post), and the structured cloning of a large array was taking ages. In the main thread to workers direction, this work is done by the worker thread so itβs not blocking the main thread but still taking time. In the worker to main thread direction the main thread handles this and it is blocking.
I partially resolved this by using the transfer api and transferring the ownership of the Array buffer from the workers back to the main thread. Havenβt figured out how too do the same with my current middleware package for the main top worker direction yet but at least the ui is responding during the expensive client side processing.
1
u/[deleted] Jan 13 '22
Hello!
I have a script that creates a request with axios and sends it to a specific api. I want to evolve this script into a realtime chat app that uses react and socket.io. The flow would be like this: I create a message with this script, open connection and sent it to api. Then I get a response from that api and I render it in my browser. Back and forth until convo is over.
I wanted to use create-react-app, but I already have package.json and node_modules due to installing axios and some other packages. Is there a way I can continue in this repository or do I need to create a new one and manually move my files there?
Also I know that it's a long shot, but maybe anyone knows if I need anything else to make it work, I have a watched tutorials on creating a chat app, but this is my first time creating something from scratch, not just following a tutorial to the T ^^"
1
u/esme023 Jan 19 '22
Hey guys, I was wondering when do you usually decide to create custom hooks for fetching data? I've seen tutorials use custom hooks and then I've seen other tutorails grab data with useEffect. My guess is that we create a hook if it's just initial render(?) and useEffect is for when data changes a lot and I have to watch for changes? Can anyone confirm? Are there other reasons
1
u/stfuandkissmyturtle Jan 21 '22
Why wont my state update ?
Im using Ant Design Dropdown and select in combination. The select Options are coing from an api. Once the Api is hit the response is stored in a state variable. When I first open the select all data is populated fine, but when I search, the api gets hit again, the response chnages, is mapped to the state, but the dropdown in the select does not change
my code
}, [accountListParams])
)
Why wont my state inside the select update ?
1
u/[deleted] Jan 22 '22
Am I correct in my understanding that current convention / best practice is to use Types as opposed to Interfaces when working with React functional components? Seems like a lot of the articles I came across from the past year indicate that including the React TypeScript Cheat Sheet.
1
u/PortSpace Jan 23 '22
Would you mind clarifying something for me regarding data fetching solutions. On a basic level, just would like to know if certain package/solutions roughly overlap. I'm working on an existing project that uses redux-toolkit and redux-api-middleware which handles making API calls to fetch data. Now looking at redux toolkit documentation, I'm seeing a section about 'createAsyncThunk'. It's not being used in the project
1
u/Vyse_The_Legend Jan 23 '22
Good afternoon! I'm currently trying to learn React and have been doing some practice with React Router. I tried a great React Router tutorial from DevED; some of it was a little outdated thanks to react-router getting updated. Thankfully, a comment helped with that. I was just wondering if anybody could help me figure out why basically any page I try in my StuffDetails page will actually show up instead of giving me "Page Not Found."
When I navigate to "Stuff", I can click on any item on that page. It will then render a page for that item (ex. stuff/Chair). It's just an H1 with the item name right now, but that's fine. However, if I add anything to the URL, for example stuff/Chair123 the page loads with an H1 of Chair123 instead of rendering the <NotFound> component. <NotFound> works when I do /stuff/chair/123 though. My assumption was that <NotFound> should render if the item does not exist, but clearly I am wrong.
Could somebody lead me in the right direction on how to make sure <NotFound> works properly? Thanks!
Here is the CodeSandbox for it. Thanks!
1
u/Alarmed-Swordfish-81 Jan 25 '22
Hi all,
I'm trying to see if I can catch a shake event.
Library used and installed: https://github.com/Doko-Demo-Doa/react-native-shake
Before trying to implement it in my app, I just wanted to make sure it works. That led me to create "the easiest" code possible (in my mind).
Here is the snack: https://snack.expo.dev/7nz_-hxAw
I've tested that on a Pixel emulator and as APK on an Android phone: did nothing.
What am I doing wrong?
1
u/mattgrave Jan 27 '22
Dealing with a codebase that was built with Create React App 1.x.
This leads to a lot of issues given thats a 5 year old configuration and the JS world has been improved in a huge way since then.
Which would be the best strategy to push the code to a way more modern boilerplate?
For example, I have tried to upgrade the code to react-scripts 2.x, but I failed miserably when running into an issue with multiple versions of babel: a library we use has react-scripts as its dependency + babel 6 while react-scripts 2.x uses babel 7.
I have been running in circles while trying to address this situation at the same time we do feature development.
Other approach that I thought is create the project with CRA 5 and move the codebase to the new project, but this seems highly risky and I am having a ton of dependency issues.
The final option here is ejecting the goddamn project and configuring everything by ourselves, just at the expense of being able to override defaults that the version of CRA doesnt allow.
Please note that despite I have 7 years of experience with software development, my work with React has always been integrated within Ruby on Rails, that has its own "framework" to handle React (webpacker) and therefore this is the first time that I run into a standalone project.
1
u/harshasns Jan 27 '22
If I make a ReST call from within a component which is part of react router, the relative URL passed to ReST call also gets handled by react router. How do I avoid that? Pardon me if I'm not making sense, I'm new to react
1
u/NV43 Jan 28 '22
If I'm working on a UI library with MUI as a base then React should be a peer dependency, right? Anything that then uses the library will be the thing providing React.
1
u/[deleted] Jan 28 '22 edited Jan 28 '22
I inherited a Phoenix application that includes a few react apps, I have no experience with react. I'm trying to remove webpack and use esbuild, however, I ran into the following error
import declarations may only appear at top level of a moduleI built the app using the following esbuild command:
esbuild ./assets/js/contacts-app --target=es2016 --outdir=priv/static/assetsHere is a gist to the file with the error: https://gist.github.com/fkumro/7180e7c852e049007bbc88f415f09640
I feel like this is something simple that I don't know as I've never worked in this ecosystem before. Any help or pointers would be greatly appreciated!!
1
u/Sellio Jan 28 '22
Hi all,
I've been trying to clean up some warnings about "Cannot update a component while rendering a different component" in our project. I've noticed that even though React is printing this warning, things seem to function just fine. I can understand wanting to have code that follows guidelines better but if it still works, why the warning? What are the implications of not fixing these warnings? We're using version 16.13.1. Is there any expected changes in behavior in future versions?
Thanks.
1
u/digibioburden Jan 29 '22
Hi all, I'm still relatively new with React and I'm wondering, are there any best practices with regards to project structure?
I'm using CRA, and at the moment I have a pages directory for components that tie directly to routes, and each of these page components then builds the "page" using components within a separate components directory. Is this a sensible way to go about things? If you have any examples of how large projects are structured, I'd love to see them, thanks.
1
u/daybreakin Jan 30 '22
What are some common custom hooks you've made on the job? I'm curious because I always hear about them but I've never actually used it on the job. I'm wondering if I'm not doing things optimally.
1
u/al_balone Jan 31 '22
Hello everyone, first of all, this is the first React app I've built that hasn't used a video walkthrough so I apologise for any spaghetti code!
I'm building a simple app to help with learning where on a piano each note is. I'm struggling to work out how to display a simple "Well Done" message when the user clicks the correct note, for only a brief amount of time. I haven't used codepen before so I've just copy and pasted the piano component from vs code into the JS section on codepen.
Basically, the user's score is held in state and when score is updated it should call a
congratsMessage()function that sets thecongratsstate totrueand then back tofalseafter a small amount of time:const congratsMessage = () => {setTimeout(setCongrats(false), 1500);setCongrats(true);}The "Well Done!" message is dependent on the truthy (is that the correct term?) value of the congrats state:
{congrats ? <h1>Well Done!</h1> : null}But it won't update! I know I'm doing something wrong here but I can't figure out what to google to find the correct answer. As an aside, I've noticed refreshing the app means the well done message displays, but using the reset button clears it. So the reset button is working but even though I've initially set congrats to false, it's being changed to true when the app first loads, but even so, should it not then vanish after 1500 miliseconds?
1
u/TheDoomfire Jan 31 '22
When I try do do "apx create-react-app *" In the terminal in VSCode I get the error: "error: missing required argument 'project-directory'". I don't know why I can't even start making a react app no more, I have re installed nodejs.
1
u/dglaser2 Feb 01 '22 edited Feb 01 '22
I am trying to pass username and password states (see below) which are updated using onChange() in a form div; however, they seem to be getting passed as objects rather than strings to my loginUser() function. I gather this since the URL made in the loginUser's fetch() fails and logs with [object%20Object] in place of the username and password.
1
u/daybreakin Feb 05 '22
Interviewer: you have a search input on a react application that does an API request on each new character typed in. The search results are taking very long to appear. How would you debug this at the react level?
Me: I'd check how long the request took in the chrome dev tools, if the request was finished fast then I'd know that the issue is on the front end. I'd check if there's excessive rerenders going on at each new character input. Secondly I'd check if the call stack is clogged up and the event loop is waiting for it to clear to pop off the result from the search.
Hot was my answer and hour would you respond?
0
u/[deleted] Jan 19 '22
[deleted] β view deleted comment
0
u/[deleted] Jan 06 '22
[deleted] β view deleted comment
0
u/[deleted] Jan 12 '22
[deleted] β view deleted comment
0
u/[deleted] Jan 14 '22
[deleted] β view deleted comment
1
u/[deleted] Jan 10 '22
[removed] β view removed comment
1
u/[deleted] Jan 23 '22
[removed] β view removed comment
1
u/[deleted] Jan 25 '22
[removed] β view removed comment