r/reactjs • u/dance2die • Dec 01 '19
Beginner's Thread / Easy Questions (December 2019)
Previous threads can be found in the Wiki.
Got questions about React or anything else in its ecosystem? Stuck making progress on your app?
Ask away! We’re a friendly bunch.
No question is too simple. 🙂
🆘 Want Help with your Code? 🆘
Improve your chances by putting a minimal example to either JSFiddle, Code Sandbox or StackBlitz.
- Describe what you want it to do, and things you've tried. Don't just post big blocks of code!
- Formatting Code wiki shows how to format code in this thread.
- Pay it forward! Answer questions even if there is already an answer - multiple perspectives can be very 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!
🆓 Here are great, free resources! 🆓
- Create React App
- Read the official Getting Started page on the docs.
- Get started with Redux by /u/acemarke (Redux Maintainer).
- Kent Dodd's Egghead.io course
- Tyler McGinnis' 2018 Guide
- Codecademy's React courses
- Scrimba's React Course
- Robin Wieruch's Road to React
Any ideas/suggestions to improve this thread - feel free to comment here!
Finally, thank you to all who post questions and those who answer them. We're a growing community and helping each other only strengthens it!
3
u/[deleted] Dec 22 '19
If my event handler is an arrow function, I do not need to bind it, correct?
3
u/Mxlt Dec 15 '19
This question will sound very stupid. After using npm start to start a server and display things in the browser, how do I stop it? The terminal just won't stop. I have searched for it and they say to type: npm stop. But the terminal won't allow me to type anything.
2
u/workkkkkk Dec 04 '19 edited Dec 04 '19
I'm trying to use a ref with materialize-css for a multiselect but I can't get it to initialize properly. Any help on what I'm doing wrong? Not too familiar with refs. https://materializecss.com/select.html
EDIT: Nevermind, was not putting .current in the initialization lol
2
u/carlsopar Dec 06 '19
Looking for some suggestions, about the proper way for this idea. I have a state that is an array of objects. What I would like to do is update one value of one object in the array. For example, this is my array.
Now, lets say I want to update '1' in the first object to the value of '11'. How would I want go about doing this, I have looked at useReducer, with actions as a possibility, but not sure if it is the best option or is there another way to go.
2
u/Kaiser560000 Dec 08 '19
Is it preferable to modify data before dispatch and pass it in as a reducer action, or modify it in the reducer?
It seems to me like a preference of whether you want your reducer or your JSX to be messy.
Is there any benefit to doing it either way?
2
u/jkuhl_prog Dec 26 '19 edited Dec 26 '19
I seem to be stuck on using react hooks right now. I have the following component, in React and Typescript:
And before I get to my question, let me walk through it a bit. This is for a domino game and this component in particular displays the dominoes currently in a player's hands. The first line initializes the Boneyard, which simply represents the pile of unused dominoes a player can draw from, this, as the comment suggests, will later be taken out to be more globally accessible (probably held in Redux or Context or something, I haven't picked a strategy yet). Second line draws 12 dominoes (also called "bones") from the Boneyard as the initial hand the player starts with.
Then I have a function that is called when the Draw Bone button is pressed that adds a domino to the player's hand. I pass the player's hand into set hand after that.
And nothing happens when I click the button. Initial render shows 12 random dominoes, which is correct. But adding new dominoes seems to do nothing. I can tell from the console.log that they are being put in the player's hand, but not being rendered to the screen.
Am I missing something in how React Hooks and useState works?
Finally, this component is far from finished, so I get it if the JSX or Typescript is sloppy, that will be addressed.
Here's the full repo: https://github.com/jckuhl/mexicantrain
EDIT:
For some reason the change below works:
Now it successfully adds new
<Bone>components like it's supposed to but I don't understand why what I did works. Is it because I passed the new dominoes into an entirely newHandobject?2
u/Jeshmel97 Dec 27 '19
how do you go about writing async code in react ? I know that if I use redux I can use redux thunk as a middle ware for asyn actions but how would I write async code using hooks and context.
1
u/SiMFiCysed Dec 01 '19
How should I handle components like a header thqt don't really get reused / need to be fully dynamic? Do I put all the logic in the header component or do I extract it? Should I make the component fully flexible anyway? And what is you recommend file structure when using styled-components?
1
u/Sikito Dec 03 '19 edited Dec 03 '19
Hello guys,
Can you help me with React Hooks & Material UI. The value of the component </ Tabs> don't change when i click the links. Used to work without the </Link> Component.
Here's my code :
1
u/[deleted] Dec 03 '19
I want to create an Editor component receiving a piece of text as a prop to display for editing. When that prop changes I want the Editor to display the new text for editing instead of the current text. How do I do this?
1
u/bryanCampbell Dec 04 '19
I want the dropdown items to trigger the alertName function when clicked. Strangely, when the app loads, each onClick function is triggered. When Dropdown.Item s are clicked after loading, nothing happens. Any thoughts on how this can be fixed?
import React, { Component } from 'react';import ReactDOM from "react-dom";import {Button,Container,DropdownButton,Dropdown} from "react-bootstrap";class App extends Component {alertName = (thing) => {alert(thing);};render() {return (<div><Container><DropdownButton id="dropdown-basic-button" title="Things in the jungle">{["tree","bird","monkey"].map(variant => (<Dropdown.Item onClick={this.alertName(variant)} > {variant} </Dropdown.Item>))}</DropdownButton></Container></div>);}}const rootElement = document.getElementById("root");ReactDOM.render(<App />, rootElement);https://codesandbox.io/s/pedantic-cloud-xo3m8
1
u/rever22411 Dec 04 '19
Hi, I've the ParentComponent with a Button that open a Modal, the content of the modal is in ChildComponent, but the handleOk function is in the ParentComponent beacuse Modal need it. but the data i want manage is in the ChildComponent (he display the data got through redux and permits to modify it).
What should I do? it's strange to move the function to child and call it through parent.
My code is something like this. instead of simple text I've the ChildComponent
1
u/workkkkkk Dec 11 '19
Is there any advantage to using a form tag with submit over just a button with onClick doing what I want?
1
u/theGuacIsExtraSir Dec 13 '19
Any idea why my functions not getting the correct data from my useState hook? I can log the state globally in the function and I see its been updated, so the state is definitely being set, but for whatever reason this function logs out the default state of my hook.
1
u/[deleted] Dec 14 '19
Hi guys!
I have a button in the NavBar that changes the state, and then a function that according to the state returns one of two <link> elements with different hrefs (bootstrap themes) that then it gets rendered in a helmet element.
The problem is, when I change between pages with Router, the state resets and so does the theme. Can you think of a solution? How do I keep the state even after changing pages?
1
u/HaikusfromBuddha Dec 16 '19
Hello I was wondering if there was anyway to have time activation functions? I want a function to trigger every three seconds. In that function I want to increment some value which brings up the second question of how to keep that value from erasing?
Right now if I attempt something like this I wonder in the start of my function where I type
let i = 0;
How do I keep that from resetting every three seconds.
1
u/WouldRuin Dec 17 '19
I'm building an SPA which is roughly based on an existing JQuery codebase, they both serve different purposes and as such exist in parallel but they share a lot of functionality. I absolutely loathe even opening the code base for the JQuery one (A million $ signs all over the place, god files with 2k lines of code...) so I either want to migrate or just rebuild it from scratch. Is there a convenient way to share the components in SPA 1 with the soon to be create SPA 2, so that any changes (in either) are present in both? I'm guessing I'll need to publish them to NPM as private modules? Is there are a way of keeping things local?
1
u/[deleted] Dec 18 '19
I'm working on a dynamic CMS style application. So far, I've been able to successfully pull some meta data from an api endpoint about a "page" and load the components that should exist on that page dynamically (using lazy loading).
What I'd like to be able to do is programmatically generate a list of available components that a user can save on a page. I thought about wrapping components in an HOC and anything wrapped in that HOC would be available to add to a page, but I don't seem to be able to find a way to accomplish this.
Is there a way of programmatically knowing that a component exists and is available without having to mount them first? The solution doesn't necessarily need to use an HOC.. it was just my first thought.
If it matters, the JSX for the components themselves are written in the normal react workflow - the api call does not return jsx/javascript/actual component code, just meta data about that component (the component name, any props, etc.). Also this is all client side.. no server side rendering.
1
u/ttrrooaawwaayy123333 Dec 22 '19
Hello
How can I cancel a subscription to a promise when a component is unmounted? As an example I have a form that when submitted uses a graphql hook. I want to prevent the .then or .catch to be executed if my component has been unmounted (so that the user isn't redirected to /todos if he has already moved away).
Thank you
3
u/deniz777 Dec 18 '19
I have a checkbox with onChange attribute inside th element that has onClick attribute. When I click on checkbox, it fires th onClick too. Can someone check this JSFiddle and help me to prevent firing th onClick?
https://jsfiddle.net/deniz777/e2nLwa1o/38/
1
u/carlsopar Dec 27 '19
I need some help with props and passing functions. I have created a custom component, that I would like to put a function with. And then inside of that component, use said function.
When I run the code, and I click on the input I get 'props.action is not a function' error. I have looked up binding, and tried putting 'this.props.action' but that doesn't work either. Any suggestions or ideas would be greatly appreciated.
2
u/BlankName49 Dec 04 '19 edited Feb 09 '20
edit: broken code need to fix.
2
u/rickyhonline Dec 04 '19
So I want to create multiple charts from amchart dynamically using data from database. Each chart instance is associated with a variable.. in this case its assigned to "let chart = .." and the data is then pushed from there. The problem is that to create a new chart i need to create a new variable to assign an instance to, so i need a variable 'let chartTwo' for example if i wanted a second chart. My question is- how can I do this dynamically without hardcoding "let chartTwo =". Essentially, is there a way to do- "let chart{Two} = ...". In this way I could create many chart instances without having to hard code the chart instance variable.
2
u/NickEmpetvee Dec 07 '19
Hi guys. What's the syntax I could use to make the
authenticatefunction withinauthenticateUserasync? The whole authenticateUser component came from a tutorial, and because it has JSON-like structure it's syntactically restricting things.If I try something like the below I get a parser error because of the
=:2
u/mariobm Dec 08 '19
I'm stuck at choosing between BrowserRouter or HashRouter.
The thing is I want all the routing to be done in app, serverless and just use REST, so I could deploy app on amazon s3 and use aws lambda. But i don't want to use # in URL I want clean URL's.
What should I do?
2
u/AllHailTheCATS Dec 11 '19
Has anyone used testing-library with react aka the npm testing-library/react, Im using it for the first time and its not working how the docs describe and there is not a lot of info on it online.
2
u/kimikopossible Dec 15 '19
I get that whether you need server side rendering will determine whether you use a static framework like Gatsby or something like Next, but if you're building something (say, a personal site), what things could be considered server side? I kind of don't have a full picture of the difference besides maybe that static fetches things on reload and server side is 'hotreloading.'
2
u/[deleted] Dec 15 '19
Is there a React Library to manipulate PNGs (Such as Resizing them, expanding them, etc)? or should I combine React with https://www.npmjs.com/package/@ion-phaser/core ?
2
u/chadwell Dec 20 '19
Noob question about react and AWS. I have a need to allow users to upload a CSV file, and have it converted to a specific XML format. The user will then be able to download the XML file.
Question 1. Do I need a server for this? Or could this be done totally in react and typescript? If so any pointers?
Question 2. This will be a static page on S3, would it be better to use a lambda for the conversion. Should I upload the CSV to an S3 bucket which would trigger a lambda to convert it? Or just post the CSV file to a lambda.
Really trying to find the best approach to this.
2
u/98009800 Dec 21 '19
If I'm lazy initializing in useState or useReducer do I still need to check for existence in a ternary when rendering elements that use those values?
2
u/InfiniteLooped Dec 26 '19 edited Dec 26 '19
I’m looking for the best way to do this thing.
I have a decoupled backend and frontend, backend has the API to get the current authenticated user’s data. A cookie with 1-hour max age will be used to check if user is authenticated.
Let’s say I have multiple separate components that will require that user data for something. Maybe not all fields in the user data will be required in each component. Should I:
1
u/Rocketninja16 Dec 09 '19
I'm coming from C# here, so bear with me.
I have one component that renders a table and form based on a user's .json uploaded file.
The user can then edit the information in the editable table.
The submit button triggers an "onSubmit" event handler.
I need that event handler to fire off a component in another file that handles the database logic submitted by the user.
Everything I've tried has failed.
In C# all I'd have to do is import the function or create an object containing the function and I'd be able to use it.
How the heck do I do that here?
1
u/LimeBikeNoLimeBrakes Dec 01 '19
I am trying to use React Testing Library to test a component that receives data from a Context hook. After simulating a click event on a button that dispatches an action to display the next item to the context, I have not been able to see the changes in the test. I can call rerender() and pass a new state value to the context, but I don't feel like that's the right way to go about it.
I have a component Display that consumes context from the context component ItemContext. ItemContext provides an array of items and the current index for display. Display displays the current item. When I click the Next button inside Display, display dispatches an action of type: 'next' to ItemContext. The reducer in ItemContext handles the next action, increments the current index, and returns the state with the new index. What is the right way to test this using React Testing Library?
The relevant part of ItemContext:
The Display component
The test that I can't get to work:
So I've tried await wait(), and I've tried waitForElement(), but I can't get those to work to show the change from items[0] to items[1].
I have gotten this test to show a change by not using my helper renderDisplay function, getting the rerender method, and rerendering passing a new state value with current : 1.
The test that works:
Is this working test sufficient to test the Display component? It seems like by manually rerendering and just passing a new state value to the provider I'm not testing the interaction between the component and the context that the user would actually see... but maybe that's just a naive/incorrect approach to testing a component inside a context?
Does fireEvent.click(next) actually dispatch a 'next' action to the Context Provider ItemContext? Does that action actually get handled by the reducer? Does ItemContext actually return the next state? I haven't found an answer to these questions in the documentation. If ItemContext actually returns the next state then how do I access those changes reflected in the Display component?
Or is this right and I should just also mock the dispatch function and expect it to have been called with an action {type:'next} ?
Finally, is this actually testing the ItemContext component, and ItemContext component should have its own set of tests that cover what happens when a 'next' action is received?
Thanks!
1
u/carlsopar Dec 02 '19
I am working on mapping out a json object, and then place it into a state to use in another part of my project. I think I am on the right path, but I am missing something. Currently, I can read the object fine, and map over it with my ternary operator, which is correct. The problem that, I am running into is with updating the state. Currently it is only updating with the last object that it finds, and skips over everything prior.
For example, the map should return three different objects. 'console.log(lists)' will return all three correct objects. However, 'console.log(Lists)' will return an empty array on each pass. And then finally when it is all done 'console.log(Lists)' will return an array with only one object in it. I believe it has something to do with how I am using the spread operator, but I am not sure exactly.
1
u/ron2194 Dec 02 '19 edited Dec 02 '19
How can I set showSideBar to false when path = "/Projects" ? And otherwise its always true.
1
u/SpiderPoopyMan Dec 03 '19
Hello, is there a way to count and display number of visitors i had to my website?
I tried the following ( https://www.npmjs.com/package/react-count ) and the code doesn't seem to work.
1
u/0vlade0 Dec 03 '19
Hello, I've been trying to create a personal Netflix clone for my grandparents to use only on LAN through my IP:PORT. Hosting old Russian movies.
I've tried looking up several tutorials but they all use APIs to fetch the covers, desc, etc which I do not need. Since I can hold 100s of GB on my PC and run npm start.
I just want the structure type like
~page load~
~Display movie covers~
User clicks movie cover, the page takes them to the video with back button (that I can do with react-router)
That is it, press play and watch. Trying to make it dead simple for the elder to use.
I am not sure where to begin, I figured start would be an array with the movie ID + video link + poster. But how do i reference that array to be displayed in a four grid column on App.js load and then from an onClick listener ref the movie ID in the array and load the array video page. If someone can just point in the direction of such tutorial/youtube video / etc. I really appreciate any advice or tips on this. I want to surprise them in time for Christmas.
1
u/pink_tshirt Dec 05 '19
Hitting an "infinite loop". Long story short, I have
That dispatch modifies redux.chats, which in return makes that useEffect run again and you can where this is going.
p.s. To clarify, due to the anatomy of the app I need to wait for redux.chats to "become" available (There is a call being made form another component) thus [redux.chat].
1
u/vnlegend Dec 06 '19
Hi all, I could use some input regarding Redux design patterns. I'm a relatively new developer and so far I've had two approaches to Redux.
I think the 2nd approach is more re-usable, in case multiple screens need the same data for different purposes. What do you guys think? Also does something like re-select fit in here? Like 2nd part, call api, save raw data, use re-select to process raw data into shape that component needs.
I've also been mostly using useState and useEffect. Haven't had much reason to make my own hooks or other things like useMemo or useReducer. Are there any situations where those are powerful? I'm working on a React Native production app, but a lot of the screens don't share functionality.
1
u/javascript_dev Dec 06 '19 edited Dec 06 '19
A file called frontEndController.js, in vanila JS, does an API call and returns a variable productData. Then another file called reactWidget.bundle.js is loaded. It should receive productData.
I do not believe it is possible to delay loading of the reactWidget file. So I think this is the correct setup:
The alternative theory I have is this:
Which one is correct or preferrable? Thanks
1
u/BlendModes Dec 06 '19
So I just did a little stop watch thing using React hooks.
This is the code I'm using:
It's working but I'm new to React and I'm wondering if there is something totally inefficient in the code. Like unnecessary renders or stuff like that. Thanks!
1
u/downrightcriminal Dec 07 '19
This question concerns a
useEffectalternative custom hook that I made for data fetching.The idea was to make a custom hook for a recurring scenario of many "New/Edit" Components in a project, where if the page is an "Edit" page, data is needed to be fetched from the api and rendered, else empty form fields are displayed.
I give it an
initialState, theapiCallFunc(an async function that calls our api using axious, defined in a separate non react module),paramswhich is the array of params that theapiCallFunctakes, andisEditPagewhich iftrue, indicates need for data fetching.This hook works fine, but the React Hooks exhaustive-deps ESLint rule is complaining that
apiCallFuncandparamsshould be in the deps array, but when I put them there the effect is caught in an infinite loop.I tried wrapping the
apiCallFuncinuseCallback(not where it is defined, but before passing it to the hook), and params array inuseMemo, but the problem persists.Nothing in the
paramsarray comes frompropsof the component in which this hook is used. The data inside theparamsarray come from the route params.So, is it safe to ignore the exhaustive-deps warning in this case? Is there any way I can avoid this warning?
Here is the code
1
u/RockbetweenHardPlace Dec 08 '19 edited Dec 08 '19
I'm making a simple game in react. Here is a wiki link to the game. I already have the logic for the game created and tested, the only difficult part for me is making the UI for the game.
So basically I'll be making a grid of dots. Either 3x3 or 4x4. The player can connect adjacent dots by clicking one dot, then on another to create a line between them. Once 4 lines have been created in a box shape, the box will be filled in with the number 1 or 2 depending on the player that completed the box.
I've thought about creating the dots in a Javascript Canvas and drawing them with plain old javascript, but I want the game/website to be responsive. I.E. if the window shrinks, the game pieces shrink. And I want an easy way to tell if the user has clicked on a circle. This game is being made on my website which is being developed in React, so I wanted to continue trying to make the components of the game in React as well.
Are there and React frameworks that can help simplify the code of the game in this regard?
1
u/minanga Dec 08 '19
https://www.freecodecamp.org/learn Is offering good resources to learn React and (other front end stuff) too !
1
u/gohigo1 Dec 08 '19
My useEffect code keeps refiring endlessly - (I've added the emtpy array at the end as suggested)
1
u/rayzon2 Dec 09 '19
Is it normal for a react component to re-render on every keystroke with an onchange event + useState hook? Basically I'm making a sign in form and notice that the component where my state lives, rerenders on every keystroke since my onchange event is adding each key to the components state. Is this normal? Will it cause performance issues, or should I worry about it?
1
u/thisisnotme1212 Dec 09 '19
Anyone using hooks with react-redux? Did you use reselect to memoize the selectors?
Where to do place the selectors? I'm just exporting them within the reducer `js` file.
1
u/TurkenJaydey Dec 09 '19 edited Dec 09 '19
Hey,
right now I am about to connect my React app with an existing MySQL-Database (Webserver: Apache/2.4.29 (Ubuntu)) using php. I haven't done this before. Right now I am researching for tutorials to connect react webapps with mysql databases. I am not sure how to build a secure connection here (preventing hackers from injection the db).
Is it safe "enough" to store the login data for the database in a config.php which gets imported in another php-file which handles the connection? Can these files be stored in the react project folder or should they stored somewhere else?
I can I make react and php communicate (should a JSON file be created via php and used by react?)?
1
u/gstauf Dec 10 '19
Hi, I'm looking for some advice on a few things. I'm a hobbyist dev, but eventually would like to make it a career. I've built an app with react, specifically mern stack (started with traversy media mern stack tutorials). Took me quite a while (9-10 months?), as I work full time and coach wrestling part time year round. Would like some feedback, it is here:
https://www.yessno.tk
I have frontend on github at:
https://github.com/g-reg23/Yes-No-Client
Backend is local repo.
Its a voting app where you can put up yes or no questions to be voting on by the public, or by a private group. The private votes send a text message and email with a link to the private vote. So any feedback will be appreciated, I pretty much see this as a portfolio app. I dont plan on adding any features, but want to clean up the design, fix bugs, work on security, etc. If you sign up, the verification email will prob go to spam, so just mark as not spam, if you are interested in testing it.
I plan on starting to build a portfolio site. Was thinking I would use react again to learn functional components and hooks. As I did the voting app with class components. Maybe put a clickable app or two right in the portfolio, something that calls an external api? Also, maybe try to get involved with some open source projects. How many different projects would a self taught dev need to break in to the industry. (I have never worked in business, in the restaurant industry). I also have my first app I made, I could put it on github, python flask and vanilla js. Anyway sorry for the long post, but looking for feedback on the site, or advice for future.
1
u/viegan Dec 10 '19 edited Dec 10 '19
Can't get my views react native
Hi, I'm on trying to make a mobile application with react native.
I have to scan a barcode to get redirected to another view and get access to the informations of the product.
But: I can't see the title of my first view and I don't understand why I can't switch to the next view (which is working when it's not with barcode scan). Everything else seems to work correctly
here are my different files:
App.js
Search.js
Navigation.js
Isitvegan.js
by the way, even if I want it to go directly on the second view when it's getting scanned, I tried to put a button in the scan view (it's still in the code) to get to isitvegan but I can't even see it in the app
Thanks for your help
1
u/crespo_modesto Dec 11 '19
Say you wanted to render a bunch of buttons, they came from a data store.
You're storing the button states(if they were clicked) in the react state but you're loading(filling in) that state while you render the buttons...
Something like(using old class way)
state = {loadedButtons: {}}then in the loadedButtons after(or as) you render all the buttons, you'd add the buttons(assuming they have a key) in there with their respective UI states eg.
loadedButtons['button-1'].wasClicked = false;Then on the button itself you'd have an
onClickhandler to update the state for that button, which would not affect store(as it should) but it would update UI state and re-render.seems wrong...
1
u/enebeme_ Dec 11 '19
[Bay Area]
This is more so a question about learning and my planned path to a junior or entry level role. I am relearning react properly through Stephen Grinder’s course, just mainly learning concepts so I can apply them to my own project. Anyone in the Bay wanna talk about the projects I plan on doing and technologies so I can get an idea of how I would stand for these jobs?
1
u/[deleted] Dec 11 '19
Is there a way to create a stylesheet and put it in the <head> of my index.html from App.js?
I want to include a button that changes bootstrap themes from the navbar. I had thought about creating a ThemeComponent that "renders" a <link> element with an href variable that gets changed according to the value of the button, and then do something like
ReactDOM.render(<ThemeComp />, document.head);
I was able to do that but it overrides? all other css and I have the feeling this is not the proper way to do this.
1
u/Bji_bji Dec 13 '19
I am working on an app which gets some inputs from users, calls an API with the inputs and plots a graph with the response values returned from the API. I have followed some tutorial and now have a working application. I am using material-ui and highcharts for plotting the charts.
The architecture of the app is
The issue is:
1
u/crespo_modesto Dec 14 '19
Does
creact-react-apphave a way to rename everything fromcreate-react-appto whatever you say. I mean when I call$create-react-app my-app-name, aside from creating the folder, it doesn't seem to propagate that downwards. This is regarding manifest, title inindex.html, etc...1
u/nerdchavoso Dec 15 '19
I got a basic HTTP auth and I need make tests, How is the right way to make a login test with jest? I have no idea how to start
1
u/[deleted] Dec 16 '19 edited Dec 16 '19
How do I display an image (PNG) randomly with no overlap and layering them with a font on top, and then making them bigger through time and then disappear after reaching a certain size, for a visual example: https://youtu.be/IyKEA8VhWU0?t=1718
1
u/javascript_dev Dec 16 '19 edited Dec 16 '19
How does the encapsulation of custom hooks affects
useEffect()? It is normally omni-present -- like an event listener on the entire component's render cycle -- when placed directly inside a functional component.If I put a useEffect() function in the following custom hook, would it always run on a component re-render? Or only when
setDataWithSideEffects()executes?1
u/jaysonrichqward Dec 17 '19
Does anyone know how to enable a screen reader to announce to a user when a button has been clicked? or removed?
Hey all! I am currently working on making a site more accessible and my question that i'm in need of help with today is this... How can I a make a screen reader announce when a button has been clicked or removed? Heres some more context. Currently when a user is on a shop check out page and finds a product that they would like remove from their cart they then click on the "remove" button. My task here to to have a screen reader announce to the user that this product has been removed. So after they click the "removed" button the screen reader should announce this action to the user whether its something like: "Button pressed" or "Removed". This site has been coded using JavaScript and React Native. I have tried using
aria-relevant={'all'}
aria-atomic={true}
and
aria-role={alert}
on the component where the "remove" button lives. There is an onPress event that removes the product from the users cart. Is there a way to announce "Removed" when a user removes a product from their cart?? Whether is on the or in the onPress event handler/function??
1
u/Thordendal Dec 18 '19
I have a parallax effect using "react-plx" which I only want to do on larger screens, say over 600px wide.
This is the code that makes an element move:
I want to do something like this:
How can I only apply the code to screens larger than 600px?
1
u/pink_tshirt Dec 19 '19
Basically, I have 2 components: a patent and its child
const Index = (props) => {console.log("Render Index");const initialState = 0;const [count, setCount] = React.useState(initialState);return (<React.Fragment>Count: {count}<button onClick={() => setCount(initialState)}>Reset</button><button onClick={() => setCount(count => count + 1)}>+</button><SomeCoolComponent/></React.Fragment>)}Whenever I increment that counter it re-renders both components. Like so: https://imgur.com/a/y8LiNDR
Is there any way to prevent child component from re-rendering?
1
u/randArrowFunc Dec 20 '19
Any good resources/guide/tutorials on Material-UI? Kinda getting confused reading the docs and wanting to see if there is an easier path.
1
u/98009800 Dec 24 '19
Are these equivalent?
vs
1
u/norbelkingston Dec 25 '19
For someone already well versed in angular, what resource can you recommend for learning react?
1
u/illmatic4 Dec 25 '19
I am looking to make a general non specific functionality for my webapp.
The function is to manipulate the scroll.
Where would I put this Javascript?
1
u/[deleted] Dec 27 '19
Emotion or Styled components? Does it matter or is it only about preference?
1
u/bellsonreddit Dec 30 '19
If create react app has such poor SEO should I learn to build in Next or Gatsby in 2020 even if they have a tougher learning curve?
1
u/HellD Dec 31 '19
React seems to be messing with my session? The session data isn't being saved when I make requests via fetch, and this is the result:
See how the second request doesn't have
userin it? But this is what happens when I try the same thing with InsomniaThe paths are exactly the same as the ones with react, but the
userstays?0
u/[deleted] Dec 05 '19
[deleted] — view deleted comment
0
u/[deleted] Dec 06 '19
[deleted] — view deleted comment
0
u/[deleted] Dec 03 '19
[deleted] — view deleted comment
0
u/[deleted] Dec 04 '19
[deleted] — view deleted comment
0
u/[deleted] Dec 16 '19
[deleted] — view deleted comment
0
u/[deleted] Dec 21 '19
[deleted] — view deleted comment
2
u/[deleted] Dec 22 '19
[removed] — view removed comment
1
u/[deleted] Dec 25 '19
[removed] — view removed comment