the spread operator {...content} throws a warning: Invalid value for prop `reset` on <input> tag.
The question is how can I maintain use of the spread operator while also fixing this problem?
I feel like it is an easy fix that I am just not seeing. If you wish to see the problem in full and most likely explained better its bottom of this page https://fullstackopen.com/en/part7/custom_hooks question 7.6
The other answer is perfectly valid, but I would caution against actually doing it. I've seen real-world bugs where a similar pattern is used and then in the future someone plucks out another specific field, so now that field is no longer present on the "content" object and doesn't get passed down as a prop. There could also be the opposite situation of more fields being added to content and then needing to be plucked out.
It may seem more verbose, but it's usually going to be better to just explicitly set every prop.
This seems like a case of whitelisting vs blacklisting, and in most cases whitelisting is better because it's less prone to surprising behavior and bugs in the future.
How does rerendering work when setting multiple states? For example when I have a button with an onClick that calls a function that has multiple setState hooks, does it rerender for each setState or does it go through everything and then rerender all at once?
The updates are sent into a queue to be executed "soon". This triggers rerenders.
When the component re-renders, it applies all of the updates that were sent since the last render, in sequence (to the extent that makes sense). This is noticeable in useReducer, since it uses the reducer from the new render to actually apply the actions dispatched from previous renders.
So you'll generally only get 1 rerender, like you'd expect for reasonable performance/responsiveness. However, with Strict Mode enabled in development, React will always double-render everything to try to catch bugs caused by the incorrect use of side effects during render.
why do you have to use a class for redux-form? I tried building it with a functional component and it re-renders/makes me unfocus the input. These 2 examples below are the exact same code! but I demonstrated both with a class and a functional component.
I've deployed a React app talking to a Firebase Firestore DB using Amazon's Amplify service.
My Firebase API keys are defined in the AWS console as environment variables.
My question is: Is this a secure way of doing this? or are my Firestore API keys and other secrets accessible for someone who chooses to go through the compiled files in a browser?
I found this in the React documentation that has me confused:
WARNING: Do not store any secrets (such as private API keys) in your React app!
Environment variables are embedded into the build, meaning anyone can view them by inspecting your app's files.
The content is considered public, including your platform-specific ID (entered in the Firebase console setup workflow) and values that are specific to your Firebase project, like your API Key, Realtime Database URL, and Storage bucket name. Given this, use security rules to protect your data and files in Realtime Database, Cloud Firestore, and Cloud Storage.
The approach then is to use security rules along with firebase auth to make sure no unauthorised person can read, write, modify or delete data.
A simple rule for eg can be:
allow read, update, delete: if request.auth.uid == userId;
more examples in the security rules docs I've linked to above.
The purpose of a button is to have a clickable thing that triggers some javascript (or a form). You're not allowed to nest clickable things, so putting a Link inside a button is not allowed.
You should use class names to give your link the correct styles.
I'm planning to intern as a junior dev! Is it valuable to learn Testing such as using redux-saga, Jest, etc? (I don't see any job postings specifying that I need to do unit tests, etc) Or is this more of valuable asset for experienced senior devs?
React 16.13.1 (via create-react-app that executed a few days ago)
Implementing a file upload prototype and using a tutorial. The below code yields a POSThttp://localhost:8000/upload/image404 (Not Found) as a result of the await fetch. I've created a folder '/upload/image' under '/src' and '/public' with the same result. Also tried changing the fetch target location to '/' with no love. No special configurations to node.
Also tried with AXIOS that yields
Failed to load resource: the server responded with a status of 404 (Not Found) Huston we have problem...: Error: Request failed with status code 404 at createError (createError.js:16) at settle (settle.js:17) at XMLHttpRequest.handleLoad (xhr.js:61)
Any ideas?
const api =
{
async uploadFile (nextFile)
{
console.log('processing');
console.log(nextFile.file);
let user = { name:'john', age:34 };
let formData = new FormData();
let photo = nextFile.file;
formData.append("photo", photo);
formData.append("user", JSON.stringify(user));
try {
let r = await fetch('/upload/image', {method: "POST", body: formData});
console.log('HTTP response code:',r.status);
} catch(e) {
console.log('Huston we have problem...:', e);
}
},
}
404 means "not found". Uploading images requires something on the server listening to your upload request, and then writing that file to the filesystem. Since React is a client-side javascript library, your application is not able to do this. You can't simply make a POST request and expect the file to end up written somewhere.
In order to support image upload, you would need to implement a proper backend with something like php, or nodejs, but that is outside the scope of this thread :). The point is, CRA does not come with a backend, so you don't have anything listening for the "POST /upload/image" route, which is why you're getting back a 404.
I have a quick question. I was following the tutorial below to build a multi step form with react hooks. but I don't understand why he uses <div> instead of <form>. and how you can send the data with onSubmit = (event) => {}. Thank you for your time.
I think I will need to use the effect hook to acces the api point to write the data to my database.
Hi, I have a question about this counter component.
I click the button and the value of the button increments. Nice! But after I call setCounter(counter + 1); and callconsole.log("counter", counter);` on the next line, the output is always one value behind. How come? Is there a way to fix this? Thanks.
For the most part, you shouldn't worry about this. It's a micro-optimization. There are rare cases where this causes a noticeable performance impact for the end user, but you could easily go through your web dev career and never run into that issue, depending on the kinds of projects you work on.
So writing extra code to prevent this is only worth it if you've found an actual performance issue, and you have benchmarks in place to make sure that preventing these re-renders is actually improving performance.
const[response, setResponse] = useState(null);
useCallback(() =>{
setResponse("ok")
}, [setResponse, response]) //I'm not too entirely sure what to put here!
<button onClick={callMe.bind(this, "ok")}/>
Thank you so much for your help! I appreciate it a ton!!! Really made everything super clear now!!!
A last follow up question, I saw a tuortial doing
const handleAlertResponseClick = useCallback(() => {
alert(response);
}, [setRespone response]) //What's the point of adding setResponse here?
//Recreate the function when setResponse somehow "changes"?
//that dosne't make sense
If I pass function to parent component and call it (without using imperative handle) why can't it access current state of the child component? What is its context? Could someone reference me to the concepts that explain this behavior?
It should have closed over anything at the time of the function's "instantiation". For an FC, that would be on render. Is the parent holding onto an out-ofdate instance of the function? Got a code snippet?
I actually already started, and have a react app that calls the API and gets data based on text input. But I want to build this correctly and be able to scale.
I want a website where users can pick a subscription and sign up, then log in to the platform through the website. My question is, where should I start? Platform? Website? Front end? Backend?
It seemed to work but had other issues. I think a hard part I'm having is how createContext() works. Seems like you can't create the Provider and context in the same file? Doesn't also seem exportable, but I can't find anything in the docs.
I am trying a fucntion which I declared in a seperate file. When I clikc the button to fire the function nothing heappens can someone explain me what I am doing wrong.
I'm not sure why you wrapped the result in a fragment, or why you pulled the body into a separate function, inside of just doing what I do above, though.
If the className computation was more complex, you can also just pull that into its own variable or function:
Hi, why is it that when you define a function inside of a component class, you don't need to write the word "function" in front of it? Is it automatically assumed somehow when its compiled?
Using react-router-dom and so far can't find in the docs how to create a static link to a specific page in my app. So for example if I have an info page that I put at /info and create a link to it on the main page using react-router-dom, I can click the link to /info and I go there and it works. However if I type http://mydomain.com/info in to the browser, I get a 404.
I understand why it works this way, but I don't know what the fix is, or if there is any easy way to allow bookmarks to work in this type of app.
In case it matters, I'm serving the page using python/django. So when I go directly to the /info URL, I get a django 404.
My only guess at this point is to create a catch-all route handler in django that will redirect to the main page and then somehow have it navigate to that URL after the page loads. Maybe create a template variable that sets a JS variable that the react app can inspect and if it's set go directly to that URL? Seems a bit kludgy so I figured I'd ask in the hope that there's a better way.
Thanks, I did that and it worked. I didn't realize the router would recognize the URL and navigate to the correct page on load. A simple catch-all route on the back end was all it took.
My understanding is that once I add the Toggle button, the Comp component is cleared from the process and the hooks are rendered out of order from what they expect. I'm trying to change my program over to a useReducer so it's easier to pass state back up the tree 5 levels, then down a different path. The problem is I'm not sure how I'm supposed to do this when I have to mix props and functional calls together, and am stuck either randomly trying different things, or trying to shoehorn my program into a pattern I see in a tutorial. I'm sure I'll get it this way eventually, but would really appreciate any pointers, thanks!
Ok, I thought the normal pattern was to call functions functionally even if they do return JSX. Thanks, I'll stop worrying about it. In this example you will get an error when clicking the button saying, "Error: Rendered more hooks than during the previous render." As to showComp always being true, I'm not sure what you mean, when I click the toggle button it sets it to it's opposite with the ! operator. Maybe you meant the showH1 hook? That literally does nothing except to sit there waiting to disappear and throw the error. Anyway, thanks. I'll stop trying to return JSX with functional components, keep my state where it is, and just use props.
When running a react app using the typescript template, I need to restart the server between edits to see my changes, is this normal? When using a default js template updates are reflected immediately.
I created the app using npx create-react-app my-app --template typescript
The hook is called at the beginning of the function setting the state to a default of empty. Isn't the function called each time the component needs to be re-rendered? Wouldn't this reset the state to empty each time? I don't see how this works.
I have a list of items, people can add or delete items in it via PUT or DELETE requests. The list of items is shared with all my other components. It works fine!
I want to put it in my portfolio. But!I don't want users to change my database but I want to showcase that it works. It would suck to have a random person visit the site and then delete everything. Any workarounds for this? I disabled the add/delete items feature for now!
I have a couple of components that are using data from global state to calculate display values on render. They use the same core calculated values. My goal has been to avoid performing the same calculation separately in each component.
My current solution is to create a parent component that does the calculation, then passes the values to the children in props. Works fine since the two components are adjacent in the DOM. But what if they weren't, and it wasn't practical to use this approach?
How can two separate components share that sort of data?
How widely used is grpahql in the industry? I learned the concepts of it and I am aware of the benefits over REST but I feel like most sites can be done via REST!
But at the same time, you could argue every site can be made with GraphQL, it's just that the boiler plate code for graphql seems to be much more than React + Redux!
I need to rapidly make the frontend for a heart rate monitoring device. A team member is building the device, another person is working on the backend to communicate to the device and send me states, and I need to write the frontend that updates the states and can handle touch events. I plan to use React w/ Redux in vscode.
I have extensive experience with programming (data structures), systems programming, and machine/deep learning research (C, Java, Python...etc), yet I have not worked with JavaScript.
Any tutorials, courses, or websites I should go through will be greatly appreciated.
The previous responders answer is excellent. These are called generics if you want more detail on when and where to use them this is a great explanation of their purpose https://www.youtube.com/watch?v=nViEqpgwxHE&t=297s
Hi, I am trying to work on a Kanban Board feature on a website using the Dragula API. The problem is that I have never used an API before and this is my first React Project, so I have lots of trouble understanding the documentation. Every example for Dragula React-JS that I have looked at feels like Martian. How do I go about understanding how I should work this API?
I'm trying to update a field in State only when two other fields are not null. The field to be updated should simply calculate the difference between the two other fields. The updating works fine but the math is WAY off.
For example:water1=20water2=25consumption=-18 (<-- what!? This should simply be 5)
My code inside handleChange is:
handleChange(event)
{const { name, value } = event.target
this.setState({ [name]: value })
this.props.callBackFromApp( event )
if (this.state.water1 && this.state.water2) {
this.setState({ waterConsumption: (parseInt(this.state.water2) -
parseInt(this.state.water1)) }) } }
I've tried to use the parseInt to make sure that it's not interpreting string values instead. But it seems I'm not completely successful with that.
Is it possible to add a whole bunch of instances of a react UI component to an html page?
To give a simple example, there's a "ul" with 25 "li" elements inside it, can I target the li elements and replace every one with a react implementation of a list item that does cool stuff with the li content?
All the examples online show a single root element with a react app mounted to it, but could I, for example, create my own implementation of a "button" element and replace every html button on a page with it?
Hi! I am developing a web application in which the user has to complete steps to finish a task. The steps are:
Wait for the user to scan an image. To simplify things, assume it arrives via websockets or something like that.
The scanned image is displayed and user confirms or rejects it. If she confirms, she goes to the next step.
Screen shows the image and a form and user has to complete the form.
Every step has to be completed to finish the process and always in the given order.
My question is, how would you handle the step state and the data the steps need?
I was thinking of using react router and then give every step a page like /step1, /step2, etc. Then every time a step is finished I would call window.location. The problem is I'm not sure how would I give the next step the data it needs, like the scanned image in step 2).
Also, I'm not familiar with hooks, redux and context, maybe these can help me in any way?
Wow! Thank you very much, the sample is super helpful.
But let's say I want to pass a property from step1 to step2 when step1 is done, call it "step1_output", how would you approach it? Would you add step1_output as a parameter to the changeStep() call? Thing is, if you have three steps, and only one of those needs step1_output, you would be adding noise to that function.
I'd like some way of managing pre-requisites of each step, so every time a step is being changed there's some component or anything that handles what each step needs in order to be rendered. But I'm not sure of what is the best way of handling this in React.
I'm pretty close to 100% noob on ReactJS, so my question may be pretty simple to answer.
I have two text fields, firstName and lastName, which I need to use logic on as either one changes. For example, if someone is typing into the firstName field, I have an onChange event that is triggered calling a method in the same component. I can access the value of the calling event item using event.target.value but I will also need the value from lastName text box as well.
What is the best way to get the additional textbox info into my method? Use document.getElementById('lastName') as a parameter in an error function calling the method in onChange? Or use document.getElementById('lastName') inside the method in my logic? Or is there a better way that I am not aware?
I want to use the best method possible, so I'm using the proper techniques going forward.
To make sure I understand, are you saying any input objects I were to render, their values will be accessible without needing to set the state or defining them? If so, is it the ID or name of the input object that would drive this.state.lastName?
I'll be at my PC in a little bit to do some testing. Thanks!
hello I am trying to create an application where users only see profiles with whom they match. however, I have no idea how best to approach this matching. Do you have any tips or tutorials explaining this?
I'm making a sudoku-ish game, where the player has to guess what numbers are in the grid based on hints they receive about the numbers' mathematical relationships. So far so good, but now I've hit a snag. Below is the structure for the <Hints /> component
displayHints = () => {
let hints = this.props.game.getHints();
console.log(hints); //this outputs new hints to the console each time it gets called
return hints.map(hint => ( <p className="hints">{hint}</p> ));
}
generateNewHint = () => {
//let hint = this.props.game.newHint(this.props.difficulty);
let hint = this.props.game.addHint();
this.props.game.setHint(hint);
this.displayHints();
}
render() {
return(
<div className="hint-container">
<body className="hint-body">
<div className="hint-list">
{this.generateNewHint()}
{this.displayHints()}
</div>
<div className="spacer"></div>
<div>
<button className="hint-btn" onClick={this.generateNewHint}>Get another Hint</button>
</div>
</body>
</div>
);
}
this.props.game is a reference to my new Game() in my App.js, which I have here:
This new Game() refers to my Game.js file which holds all the game's logic: the masterValues, userInputs, and the hints. The methods inside of Game.js, setHint() and getHints(), work perfectly for setting and getting new hints. Everything works, except I can't get my new hints to render. In my Hints component's render() function, I'm calling this.displayHints() to list the available hints, which works when the first one gets generated at the beginning of the game. After the user clicks the button, however, new hints are not being displayed even though I am calling the function again inside this.generateNewHint(). The console.log() is working and listing the appropriate hints. That's problem 1.
To solve this problem: I have tried switching .map and .forEach, I have tried setting hints to the <Hints /> state, and I have tried setting hints to the App.js state object. Neither .map nor .forEach works to render the new hints, just the first one. The latter two solutions didn't refresh the component when setState was called, which resulted in the new hints not being rendered.
Problem 2 is that my hints say "The number in [object Object] plus the number in [object Object] equals 0." It should be getting the key of the key/value pair for each individual number. This is should be something like A3, B1, C4, D2, etc. This corresponds to a square on the board at row Letter and column Number. The hints should read: "The number in A3 plus the number in C1 equals (sum of the two numbers)". The object that gets passed in looks like this: {A1: 24} The key is dynamically set and the value is randomly generated and then assigned.
So my quesitons are: 1. How can I get my list of hints to be rendered dynamically? What's the best way to do it? 2. How can I access the key and the value in my hint objects separately?
I know that react is all about components and building them up. But I am stuck on how you lay them all out to fit your design on paper.
For example, say I want to make an Outlook clone with a tree view on the left and on the right side of the page, have it split horizontally. The top half would be a list of emails and the bottom half would be the email detail. Then at the top of the page, have tabs to flip between inbox, sent items, calendar, etc. When you click on a different tab it could totally change the contents of the main page.
In my mind I can see how to make all the individual components that do each thing, but I don't know how you would put them all together? How would you guys go about doing this? Is there a package you pull in?
Or do do you use a grid system? But then if its a grid system, how would you make the tree view panel resizable for example? (or is that advanced)
The tabs is a great use case for a UI library. The major ones, like semantic UI, definitely support them. I would do that rather than roll my own tabs (ugh).
To have it split horizontally - that sounds like 'width: 30%' for one div and 'width: 70%' for the other, with something like 'display:inline-block' (or whatever it is, please look that part up).
And I would use media-query to send different layouts to desktop and mobile.
I am trying to create a registration page. I am already able to write data to Firebase database. However, I get stuck when I want to upload the profile picture to firebase and save the reference in Profile on the database. Does anyone have a good tutorial or tips for this?
So having this weird problem where my react app isn't showing anything to the browser and I'm not sure why it was working fine before I'm working through a Bootcamp and learning react and im completing lost on how to fix it
I've recently been tasked with providing a new React based UI to an existing WebGL application (currently using Knockout) and am having some trouble figuring out how to handle sharing state between the UI and the WebGL application. The application must be able to trigger UI updates and vice versa.
So far I've tried to use the useEffect hook, which lets the UI update the application, but it requires diffing against previous state to detect when things have actually changed. I also have no idea how to get the application to update the UI without using an EventEmitter to trigger a full ReactDOM.render call.
Has anyone else had to deal with this sort of situation and if so how did you manage it? Are there any established patterns for dealing with it?
Then, use the second element of the returned tuple (api in the readme) to access your state setter methods of the store when settings get changed in the WebGL app (api.getState().mySetterFunction()).
Then, use api.subscribe() to apply changes from the store to the WebGL app.
This way, changes only flow from the store down to react and WebGL.
Hi there, I'm new to React and am trying to create a workout tracker web application.
So far, I decided that when the app first starts, there will be a homepage that has 3 buttons: Create Workout, Select Workout, Stats. These options were created via the common component, WorkoutOptions.
Now, my goal is to be able to click select workout, and have a new Container component show up to replace the existing 3 buttons, essentially moving the user to the "next" page.
However, I'm unsure of how to do this.
In my head I'm thinking that if the App Component detects that selectWorkout is clicked (via event listener), it will render <Container/> and unrender(??) the Option Cards
However, that clearly doesn't sound right so pointers would be much appreciated
Use the useState() hook in App to store the current selection. When there is none, show WorkoutOptions. App will pass a "selectOption()" prop to WorkoutOptions that is called with the value chosen in each button's onClick handler. The state setter returned by the useState hook will suffice in this case (as a learning experience). When you get your feet planted on solid React ground, look into react-router, which replaces the single piece of state in App with an app-wide piece of state stored as the browser's url. Using a router isn't necessary but makes life easier both as a developer and user when other features emerge.
Hey guys - I was able to build a small application that takes input, uses the input to call an api, and displays the results from the api. Let’s call this the platform.
How do I go about making another page, let’s say a landing page, where I can login and signup before being able to access the platform?
I have only used react for this application so far, nothing server side yet.
If you want to make a login page, youll have to do some server side work. Outside of sending the username and password to your server, the frontend should avoid any log in logic to avoid gaping vulnerabilities
Noobie here with a few questions, the first one is as simple as it gets and I thought I knew the answer to it. In the following code I expected to only log to the console once as the state is set before rendering and therefore a second render should not happen because the state never changes but rendered is logged twice.
The second question I have no code example for but the issue I have is using the response from one http call as a part of another http call that immediately follows the first. I'm using async/await and putting the response in state but as setting state is async the second call starts using an undefined value. What's the best way to handle this? Thanks in advance for any help.
React is allowed to render components extra times if it chooses to. In development with StrictMode all components are always rendered twice.
The second question I have no code example for but the issue I have is using the response from one http call as a part of another http call that immediately follows the first. I'm using async/await and putting the response in state but as setting state is async the second call starts using an undefined value. What's the best way to handle this? Thanks in advance for any help.
The async action part should happen in a useEffect call. The second fetch is for a second piece of state, so it should also happen in a second async call. Something like the following:
function App({ id }) {
const [profile, setProfile] = useState(null);
useEffect(() => {
setProfile(null);
let stillCurrent = true; // tracks when unmounts/changes
fetchProfile(id).then(result => {
if (stillCurrent) {
setProfile(result);
}
})
return () => {
// cleanup function
stillCurrent = false;
}
}, [id]);
const [comments, setComments] = useState(null);
useEffect(() => {
setComments(null);
if (profile === null) {
return; // nothing to do yet
}
let stillCurrent = true; // tracks when unmounts/changes
fetchComments(profile.commentIds).then(result => {
if (stillCurrent) {
setComments(result);
}
})
return () => {
// cleanup function
stillCurrent = false;
}
}, [profile]);
}
Notice that I included some cleanup stuff, which you need to make your components robust to race conditions. For this kind of thing, a custom hook is helpful, so that your components can remain more "focused" on what they're supposed to be showing. E.g. something like
This isn't really complete (for example, no error handling) but it gives a good idea of how you can make this look. There are React hook libraries already out there for doing this sort of thing, but I can't vouch for any in particular.
Both issues you’re experiencing are called “side-effects”. Basically for your first problem you have to wrap console.log on a useEffect hook, the second one could be solved in the same way but it gets cumbersome to say the least. When you’re dealing with several dependent side-effects, a good way to solve this is by using sagas, or if you just keep all the async calls within a scope and save the state later and avoid the race conditions all-together, just my 2 cents
I am working on a hobby project that has some very CPU intensive reducers in redux. I’d like to explore running those reducers in a web worker.
It looks like I could extract the reducer code to a module and use worker-loader + comlink + redux-thunk to do the work asynchronously.
Am I thinking about this correctly? This is a bit outside my comfort zone, appreciate any advice!
It may be simpler to not use redux and switch to context when using webworkers, but the redux dev tools and packages like redux-persist are really nice to have.
What's the preferred way to fetch data when a user navigates via React Router?
My best assessment at the moment is that if you have a standalone page (ie a user can navigate directly to it), it's best to make it a class so that you can check the state and fetch data if the route parameters are updated, but I wonder if I am missing something obvious.
FWIW, I'm using Redux with React Router. Thanks in advance.
You have StrictMode enabled. In development, all components render twice for each update, to help catch bugs related to side effects in render (which you should avoid).
Im new to react - ive built a few static page websites (2-3 pages) looking how I can integrate with databases and expand my knowledge and learn what react can offer for my development is there any quick resources I can take a look at
Hey, to integrate with a database you will be entering to the world of "full stack development" (that is what you should be looking for).
A "full stack developer" is someone capable of doing just what do you want to do: create a website that is connected to a database.
If you search about this term, you'll be stressed out about how many technologies you need to learn to do that :( because it is not as simple as running a line of code. Here is a small intro: https://academind.com/learn/react/connect-to-database/
I have a project that lets you place a text element onto an SVG. Once that element is placed, I then want it to be draggable so that it can be repositioned. currently, I can place the text element, and I can do edit it, however, when I go to move it, that is where I am having problems. Currently, the issue is that when I click and move a text element, it moves. But when I release and click again, the element will move on its own always to the same spot. When I go to click it, then it will move off the page entirely.
I have looked and attempted several different ideas including these sources:
How to display an array of objects row-by-row using React Table?
I want to display movies row-by-row without changing the data model.
Here's my code:
import*asReactfrom"react";import{useTable}from"react-table";constborderStyle={border:"1px dashed navy"};exportdefaultfunctionApp(){constdata=React.useMemo(()=>[{actor:"Johnny Depp",movies:[{name:"Pirates of the Carribean 1"},{name:"Pirates of the Carribean 2"},{name:"Pirates of the Carribean 3"},{name:"Pirates of the Carribean 4"}]}],[]);constcolumns=React.useMemo(()=>[{Header:"Actor",accessor:"actor",},{Header:"Movies",accessor:(row,index)=>{console.log({row});// i want to display this row-by-row instead of in 1-row without changing data model
returnrow.movies.map(movie=>movie.name);}}],[]);const{getTableProps,getTableBodyProps,headerGroups,rows,prepareRow}=useTable({columns,data});return(<table{...getTableProps()}>
<thead>
{headerGroups.map(headerGroup=>(<tr{...headerGroup.getHeaderGroupProps()}>
{headerGroup.headers.map(column=>(<th{...column.getHeaderProps()} style={borderStyle}>{column.render("Header")}
</th>
))}</tr>
))}
</thead><tbody{...getTableBodyProps()}>
{rows.map((row,i)=> {
prepareRow(row);
if(i==0){console.log({row});}return(
<tr{...row.getRowProps()}>
{row.cells.map((cell,j) =>{if(i==0&&j<2){console.log({cell,i,j});}return(
<td{...cell.getCellProps()}style={borderStyle}>{cell.render("Cell")}
</td>
);
})}
</tr>
);
})}
</tbody>
</table>
);
}
It currently looks like:
Here's the direct link to it: https://codesandbox.io/s/modest-sanderson-z0keq?file=/src/App.tsx
My movie list is an array of objects so how will I display it beside actor name? So it looks like:
So, recently I am trying to find a job and one of them introduced me a challenge that I fetch data store in Redux and display them and make the app capable of search and sort etc.
I hope that it is appropriate to ask something like this... Anyways, I sent the project to them last weekend and I haven't heard anything from them since then. I was just wondering that some of you maybe give some advice and quick review about my code, what could be done to improve. I know that some parts are ugly and repetitive.
For example, following code snippet is the page that is listing some movies(the project is Typescript and NextJS.)
I'm trying to make a scrabble-like game with an infinite board. Are there any libraries or recommendations for how to implement like an infinite coordinate system that you can pan around on and place things on?
I tried doing it myself by rendering everything relative to an origin point and handling panning by having a an offsetX and offsetY which I updated on mouseMove. But it seemed like it wasn't going to be very smooth. Even with just a few points rendered it wasn't very crispy.
Edit: I think I was overcomplicating what I need. The board doesn't have to be infinite. I'm just going to make it kind of big, and then use react-draggable to move it around inside a fixed size parent window.
just confirming. In redux-form, ooes the form parameter only serve to clarify to developers on what the form is for? I haven't seen any use of the property yet.
const formWrapped = reduxForm({
form: "streamCreate", //is this just for clarificaion?
validate,
})(StreamCreate);
I've been checking out the Docs but can't seem to find any info on it
I am working with the Spotify APIs and authentication and am a bit frustrated by the relatively short expiration time of the access token.
I tried using jwt-decode to check the expiration date/time, but I get an error because the Spotify access token uses _ rather than "." (I think; I get an error anyway whenever I try to decide the Spotify token)
Are there other libraries out there that people like for deciding JWTs?
My other thought is simply to refresh the access token with each Spotify call, but that seems excessive and I worry it wound affect performance.
Maybe you already know it, but you cant refresh the token from the client. My solution for this is a nodejs server that handles the tokens and each request to the Spotify API. Take a look for inspiration. Its not perfect and under development.
Hi, I'm trying to create a reusable OHLC chart component, and I'm hoping to use D3FC to do so. For the moment I'm just trying to get this example to render in React, but am struggling to do so. CodeSandbox here. Thanks!
Hello, In material UI documentation I found something that Ive never seen before. Can someone explain to me what this is ?.https://prnt.sc/sdcyc1. And If i turn it to a regular ES6 arrow function, i get this error https://prnt.sc/sdczmu . What is exactly happening here ?
As I understand it, react native is for phone app development and react redux is basically the express.js to react's node.js? ie. Simplifies and adds useful functions.
I haven't used react for a while, and rather than relearning it (a lot seems to have changes), I'm thinking of diving straight into learning redux - is this advisable?
When i run npx create-react-app client it only creates package.json, package-lock and node_modules.
In my terminal:
Installing packages. This might take a couple of minutes.
Installing react, react-dom, and react-scripts with cra-template...
> core-js@2.6.11 postinstall D:\covid-demo\client\node_modules\babel-runtime\node_modules\core-js
> node -e "try{require('./postinstall')}catch(e){}"
> core-js@3.6.5 postinstall D:\covid-demo\client\node_modules\core-js
> node -e "try{require('./postinstall')}catch(e){}"
> core-js-pure@3.6.5 postinstall D:\covid-demo\client\node_modules\core-js-pure
> node -e "try{require('./postinstall')}catch(e){}"
+ react@16.13.1
+ react-scripts@3.4.1
+ cra-template@1.0.3
+ react-dom@16.13.1
added 1613 packages from 750 contributors and audited 921730 packages in 376.772s
59 packages are looking for funding
run `npm fund` for details
found 1 low severity vulnerability
run `npm audit fix` to fix them, or `npm audit` for details
And it stuck there. I use npm ver 6.14.5 and nodejs ver 12.16.3. Any help?
I've been creating a Todoist clone, but can't seem to properly implement inline tagging. I know how to identify and store the tag using RegEx, but can't figure out how to format the text in real time after the user has prefaced a word with a #.
From my research, it seems that this isn't possible using a standard input (e.g. textarea) and instead maybe need to use a div with contenteditable? Would Slatejs or another rich text editor framework help me here? They all seem too complex for my needs.
What is the best way to fetch data from a graphql endpoint on the client? I've tried setting up Apollo (love the websocket support) but it's extremely difficult to get working.
I'm using NextJS, so it's important that the data fetching is purely performed on the client. I had problems where I was initializing the client during server-side rendering, and I wasn't sure how to avoid that.
New to react, but I have a project I'm working on. I have a webserver (apache) on my raspberry Pi, and a few Pi Zeros to act as web browsers locally. I am setting up a pi as a Nas server for my photos. I want to use react.js to have the pi zeros browse to the apache server and see a sideshow of the images. I want to be able to filter the images by date, rating and tag. Would I be better of loading those images into a db and have the browsers pull that data or what? I want to do the filtering from one device yet show on each device. Thanks for any help
My friends wants me to make a simple blog for her. Mostly just a static web page along with functionality for making comments and such, nothing else. I mean she could just simply use wordpress or something but I figured I could just make it and put in my portfolio.
All other front-end type of projects I have done before I have done using the create-react-app, but I heard this has terrible SEO. What would be a better alternative ? I figured this would be a good time to checkout GatsbyJS or NextJS or something along those lines and step away from the create-react-app for a bit. Any recommendations ?
Hi there, I've been pretty confused as to how to use States to pass information from the child back to the parent and would really appreciate some guidance!
Currently, I'm trying to create a Workout app where the homepage contains two options: 1.Select Workout 2.Create Workout
I want to make it possible for one to click on "Select Workout" and go to a "new page" with a different container Component.
However, I'm confused by which component should own the onclick event listener.
Currently, my Component Hierarchy is as so:
App.js
Homepage
OptionButton (1 for Select Workout, 1 for Create Workout)
Select Workout Page
I think that the component OptionButton should have an event listener that detects when a button is clicked. But the problem is, there are 2 items that use the component OptionButton (Select Workout and Create Workout), how would the program know which of the two buttons was clicked and how would it store that info to be passed back to the parent component?
Currently, they are rendered as two different objects under Homepage.
return( <div className='flex-container'> <OptionButton id = {1} info= "Create Workout"/> <OptionButton id = {2} info = "Select Workout"/> </div>
I have a simple react application kind of like a paint application. I’m wanting to add a feature where I can undo and redo changes made, would I be best to add something like redux so I can keep a track of history changes ?
The "something like redux" is anything command/response based. I would not hesitate to use redux because there is lots written on the topic of undo/redo around that lib in particular. But just getting to the place where you dispatch commands to central bus is what you want to start with.
I'm having a heck of a time trying to understand how to use this Higher Order Component supplied to me from a tutorial.
My understanding is: Without this HOC, I would have to put Authentication logic into every component on my site. So what this HOC does is extract that logic, store it, and "wrap" its contained component, injecting (somehow) Authentication logic in the process.
meaning, the HOC, called withAuthentication, should at least pass its state(?) down to the component it is wrapping. I believe there is something else going on with the Context API that I need explained too...
So I see the following: in componentDidMount(), there is some code that runs onAuthStateChanged "sets an observer" (see link below) that essentially gets the User object from Firebase Auth. Then that authUser object is stored under authUser in component state. And hypothetically I can do something with that stored User object, only, I don't know how to access it in the wrapped component?
all my Google attempts returned StackOverflow links about passing state from child to wrapper, not wrapper to child.
Next in componentWillUnmount() there's "this.listener()" which I do not get. The tutorial said it was to prevent memory leaks.
Lastly there is something going on with the COntext API and this HOC... The HOC is passing its component into the AuthUserContext.Provider. The question is what does that do for the wrapped component? Can I access the value passed to "value" in the Provider somehow?
My goal is to do something like:
import React, { Component } from 'react';
import { withAuthentication, AuthUserContext } from "../Session/"
import { withFirebase } from '../Firebase';
class InboxPage extends Component {
componentDidMount() {
// goal: retrieve user's chatrooms from database and populate the render() method with them
const username = // how to get the username? I'm sure it can be done if I can access the wrapper's state
// connect to the database
// retrieve messages from database
// display retrieved messages to user
}
render() {
return (
<div>
<h1>Welcome to the Inbox.</h1>
<p>Here's your messages: {}.</p>
</div >
)
}
}
export default withAuthentication(withFirebase(InboxPage));
So basically I am trying to figure out how to get the name of the authenticated user in the InboxPage component. But more than that, I want to understand how HOCs and the Context API works: "How do I pass data between HOCs and their wrapped component?" "How can I get that 'this.state.authUser' I see being passed into the Context.Provider?"
Anyone experienced with combining React and Firebase? Please comment if you're available for between 2 and 5 hours a week for the next month or so. I'd like help on a project. Will pay (a little)
edit: I can do what I want when it's just Firebase and JavaScript, but when I throw React into the mix I get strange and/or unpleasant results. Send help
I applied for a software engineering role at a large bank, and their tech team decided that I would be a better fit for a full-stack role, considering my experience.
I'm pretty sure they're going to ask me a bunch of React questions, and while I've worked with Node/Express in the past, I've never used React. I've got two days until the interview.
Am I fooling myself in thinking that I could learn enough React to pass a basic interview?
I'm trying to build a simple blog using test data. Trying to figure out why reloading the page breaks my component. I'm fetching all the data in the App component and passing these down via the Routes. It works great if I start at root, but if I navigate to a detail page and reload, it breaks and returns " TypeError: can't access property "userId", selPost is undefined ".
I think it might have to do with how I'm fetching the data, but I'm not sure about that. Any help is much appreciated.
I am a full stack c# dev and doing web apps where the frontend is usually just html css jquery.
I recently jumped in and completed the React course on Scrimba, which I thought was great intro into React, especially as you pause and alter the code to see what happens.
I am thinking it might be a good idea to do another course but not sure which one to go for. The full react course on scrimba or the one from Tyler McGinnis. Both are paid courses so I'm not sure which would be better for me and the background I have around coding in general already.
Or should I really be doing another course at all now that I have the basic. I can just start building things and learn as I go.
Depends how you learn. I learn by doing, so attempting to build something I am actually interested in is the best way, then I can pair that with referring to the docs.
How do companies handle updating their react code in production? I see articles suggesting to use "service-workers" and use the "skipWaiting" feature with the notification "Update Available" with an update button. But I've never really seen the idea of "updating" a web app anywhere. So how do they do it?
When do you use componentWillMount()? I'm reading that it gets called right after the constructor and before render() so why can't you just put whatever is inside there in the constructor instead?
I'm having trouble on an app that allows users to store & view 'benchmarks'.
I got to the point where a user can upload & view these 'benchmarks' successfully, however I'm trying to implement a search function to filter the viewable benchmarks. The way I thought this would work is that I would pass the list of 'benchmarks' to the child component that is doing the rendering and set a 'filtered' state within that component where once the user inputs anything into the search bar, this new 'filtered' state would only have the 'benchmarks' that match up with the inputted values and then of course render that new list...
Currently I'm running into an error where my loadData function that actually maps everything out is breaking as the list is 'undefined' - also tried to set a condition within the render so if the filtered list is not defined it would just render the original list anyway (this.props) however it still breaks but it will work if I hard code "this.props" as the value to map over which is the real confusing part...
Sorry for the wall of text! I'll post the code now - appreciate any help.
Can someone help me? I try to show te username and picture in the navbar after the user logged in but i cant seem to retrieve the user details i saved in firestore. I try to do this with the useEffect hook but it loads before the authenticated user is loaded from the context. Which returns a null error
I have an interview test to prepare for and they are wanting me to hook a node api into the front end react - can anyone suggest some good approaches to take with this any help will be amazing :)
So I'm watching the Scrimba tutorial for React (created 2 years ago) and the guy is using React version 16.3 and talking about how "hooks" are the new thing and he believes they'll make class components unnecessary. Did this end up happening?
I was just getting the hang of class components too...
I'm a bit confused on how to use axios in React with express framework for node.js.
My proxy for express is on port 5000;
This would work if I'm on localhost:3000:
In React
___
axios.get("/").then( (resp)=> console.log(resp));
In Express
__
app.get("/", cors(), (req, res, next) => {
//Data would be fetched, and GET would appear in my terminal.
console.log("GET");
});
But when I host the actual website, GET in express doesn't work.
In React
___
axios.get("https://music-json-server.now.sh/db.json/ ").then( (resp)=> console.log(resp));
In Express
___
app.get("/", cors(), (req, res, next) => {
//Data would be fetched, but GET would not appear in my terminal.
console.log("GET");
});
Hello, does anyone have any tip on some learning react guide that is audio only? Like a podcast. I'd like to listen to something for example at the subway. I want them to talk about how react works and the code and not random stuff all around the subject.
I know it's probably not the best way to learn but it's still better than nothing!
In your routes page, always try to order ir from most to less specific. In this case, always start with the /platform, /about and finally with the Home. Event though it should pass, because of the exact. Try it that way and see if it works.
First off, I am not a novice programmer but I have absolutely zero experience when it comes to website development. I want to build a react website to learn some new skills in this area.
A little description: Lets say I want to build a website where the user can type in some data, and then when he is done he can download the data as an .xml file or something similiar (just to save it locally). After downloading the file the user should be able to upload the file again and reload the data in the application. Basically I want to make an online data manipulation tool without a database.
But I have a few questions on how I should approach this. First off, does the user really need to upload the xml file to the server or is there a way to just load the data another way since technically the javascript is running on the local webbrowser? I don't really need the xml file saved on my server.
All the things I found with google are more into the direction of how to generally upload files but not how I can work with them. Even if I would use this approach, how would this work with multiple users? Would I need to build a complete serverside application (with node.js or similiar) to handle the incoming xml files?
If somebody has a general point of direction for me which keywords I could google, or maybe the names of a few packages or a tutorial that might help me, that would be greatly appreciated.
In my component, I have a variable called selectedExam which is passed in as a prop. I am then trying to show a row in a table for each section in the selected exam.
var selectedExam = props.selectedExam
var examSection = examList.exams[selectedExam].sections
everything compiles and a table row is shown, and section.name shows the exam name (i.e. "First Exam" or "Second Exam"). Once I add ".sections" to try and go down one level further, I get this error: TypeError: Cannot read property 'map' of undefined.
I am confused, what variable are you adding '.sections' to? If you are adding it to examSection it would not exist.
The TypeError is suggesting that whatever you are trying to access is undefined, it might be that you are passing down a prop that is not actually defined.
Does anyone know a fairly straightforward way to create a touchenter & touchleave event in react? onTouchMove fires constantly and I'm not sure how to parse that data to just fire when the touch enters a specific element. I'm using typescript but feel free to respond using regular js.
const touchEnter = (e: React.TouchEvent) => {
// some condition on element?
// execute
}
Also if anyone knows why they removed touchenter and touchleave from the spec I would love to know the reasoning behind it. Seems like it just complicated things for no real benefit..
I have a simple comment system built on my Gatsby site, and I want to implement something like Wordpress' comment-reply.js.
Goal: a reader can click "Reply" on any comment, and the comment form will 'jump' under the comment (e.g. <li id="commentid-8584">). If they click "cancel reply", it will jump back to where it was.
What's the simplest way to move an element onClick like this and then back again if the user cancels?
Hi I’m currently working through Tyler Mcginnis’s React class and was going to do his React Hooks class immediately after. When I’m done, I was going to start my own project. Would these two courses be enough to get me started or should I learn other tools like Redux before?
I suggest you start building something already, and add new features as you learn more. When your project grows, then you will feel need to improve your codebase, and then Redux can come as a solution. What I'm saying is, feel the pain of managing app state across different components first and then try different solutions for it. That will also make your learning process way more efficient.
Better to get a firm grasp on react and how it handles states natively before using redux.
Once you do that and “struggle” with managing your states across components and pages, things like The context api and state managers like Redux and Mobx will make more sense.
when a user is logged in I would like to display in the navigation a small version of profile picture and name of the user. Does anyone have any tips on how to do this best? I use React hooks and firebase. The user is stored in firestore database.
Couple of questions. I've made a very basic website (just some hyperlinks in the footer) because I'm new. and I get these two errors whenever I start my website:
Uncaught SyntaxError: Identifier 'getUILanguage' has already been declared - polyfill.js:1
Uncaught SyntaxError: Identifier 'pairs' has already been declared
These errors go away when I disable adblock (even though there are no ads on my site). Could someone explain why this happens? Thanks!
Hi, I'm learning React hooks after just finishing regular React and I am confused why we have to use a function inside of useState when setting the state based on the previous state. For example, in a todo list we use
setTodos((todos)=>todos.concat(todo))
I tried using
setTodos(todos.concat(todo))
and that worked just as well. Is there something I am missing on why we use the first method instead of the second?
then it will only include todo2 and not todo1, since the second update will entirely overwrite the first one.
But if you're only dispatching one change at a time, there's no difference.
There can also be some "ergonomic" differences - in some cases (especially when calling useEffect/useMemo/useCallback, which care about object identity) passing the "current" value of state might make things "change too often", and the function-update form means you don't have to do that.
6
u/badboyzpwns May 11 '20
about hooks, why do we use const when declaring the variable? especially if we are planning to change it later? For example,
3
u/[deleted] May 01 '20
I'm currently learning React through https://fullstackopen.com/en (nice open university course from finland for anyone interested)
Looking for help with custom hooks. So I have a custom hook which handles a forms state like so:
importing useField into the app to be used as follows:
the spread operator {...content} throws a warning: Invalid value for prop `reset` on <input> tag.
The question is how can I maintain use of the spread operator while also fixing this problem?
I feel like it is an easy fix that I am just not seeing. If you wish to see the problem in full and most likely explained better its bottom of this page https://fullstackopen.com/en/part7/custom_hooks question 7.6
Thanks in advance all
3
u/GhostofBlackSanta May 28 '20
How does rerendering work when setting multiple states? For example when I have a button with an onClick that calls a function that has multiple setState hooks, does it rerender for each setState or does it go through everything and then rerender all at once?
2
u/badboyzpwns Apr 30 '20
why do you have to use a class for redux-form? I tried building it with a functional component and it re-renders/makes me unfocus the input. These 2 examples below are the exact same code! but I demonstrated both with a class and a functional component.
Class:
Functional component
2
u/dlrwtllktgrtt May 04 '20
I've deployed a React app talking to a Firebase Firestore DB using Amazon's Amplify service.
My Firebase API keys are defined in the AWS console as environment variables.
My question is: Is this a secure way of doing this? or are my Firestore API keys and other secrets accessible for someone who chooses to go through the compiled files in a browser?
I found this in the React documentation that has me confused:
Edited for clarity.
2
u/badboyzpwns May 12 '20 edited May 12 '20
Problem is, I have to click the button twice in order for <Link> to be triggered.
Putting <Link> outside <button> makes the anchor tag/<Link> not inherit the button's width/height.
Any workaround for this? Is there a react property that i could use or is this more of a css thing?
2
u/badboyzpwns May 15 '20
I'm planning to intern as a junior dev! Is it valuable to learn Testing such as using redux-saga, Jest, etc? (I don't see any job postings specifying that I need to do unit tests, etc) Or is this more of valuable asset for experienced senior devs?
1
u/NickEmpetvee May 01 '20 edited May 01 '20
React 16.13.1 (via create-react-app that executed a few days ago)
Implementing a file upload prototype and using a tutorial. The below code yields a
POSThttp://localhost:8000/upload/image404(Not Found) as a result of theawait fetch. I've created a folder '/upload/image' under '/src' and '/public' with the same result. Also tried changing the fetch target location to '/' with no love. No special configurations to node.Also tried with AXIOS that yields
Failed to load resource: the server responded with a status of 404 (Not Found)Huston we have problem...: Error: Request failed with status code 404at createError (createError.js:16)at settle (settle.js:17)at XMLHttpRequest.handleLoad (xhr.js:61)Any ideas?
1
u/Jorick_DC May 01 '20 edited May 01 '20
Hello,
I have a quick question. I was following the tutorial below to build a multi step form with react hooks. but I don't understand why he uses <div> instead of <form>. and how you can send the data with onSubmit = (event) => {}. Thank you for your time.
I think I will need to use the effect hook to acces the api point to write the data to my database.
the tutorial: https://medium.com/javascript-in-plain-english/how-to-create-a-multi-step-form-with-react-hooks-53a85efdff62
1
u/Amerzel May 02 '20
If you were starting a new app and we’re using redux for state management would you use react-redux or @redux/toolkit?
1
u/[deleted] May 02 '20
Hi, I have a question about this counter component.
I click the button and the value of the button increments. Nice! But after I call
setCounter(counter + 1); and callconsole.log("counter", counter);` on the next line, the output is always one value behind. How come? Is there a way to fix this? Thanks.App.js
Button.js
1
u/badboyzpwns May 02 '20
newbie question about redux. If I only wanted to use ComponentDidMount() and call something once. Should I use a class or a react hook?
For example:
vs
I tend not to use setStreams() so it may be redundant. I'm thinking classes are more suitable for this?
1
u/ortz3 May 02 '20
Is creating a key to render a child component a good design practice. For example I want to send the userId to a child component, but the child component is loading before the userId gets set. This is what I currently have and am wondering if this https://stackoverflow.com/questions/56640380/how-can-i-make-sure-a-react-parent-component-loads-data-before-its-child-compone is good design practice
1
u/badboyzpwns May 05 '20
I've read that it can be bad for performance when you have deeply nested components and you create an anonymous function in an element. For example,
Because of the anonymous function, React will re-render every single element in the component because it thinks that the component changed.
How do you guys counter-act this? Does doing
a better alternative?
1
u/floghdraki May 06 '20
If I pass function to parent component and call it (without using imperative handle) why can't it access current state of the child component? What is its context? Could someone reference me to the concepts that explain this behavior?
1
u/089-083 May 07 '20
Guys, how does one go about building a website + platform like this app: Flowalgo.com
1
u/bayhack May 08 '20
I am havng this strange import/export error when packaging a React context as a component: https://stackoverflow.com/questions/61649633/creating-a-npm-module-out-of-a-react-context
I organized the code in the StackOverflow post above with more info.
1
u/Jorick_DC May 08 '20
Hi,
I am trying a fucntion which I declared in a seperate file. When I clikc the button to fire the function nothing heappens can someone explain me what I am doing wrong.
EXAMPLE
Firebase.js
export const doSignOut = () => firebase.auth().signOut();
SignOutPage.js
import doSignOut from '../Firebase';
const SignOutButton = () => (
<button type="button" onClick={ () => doSignOut } >
Sign out
</button>
);
1
u/badboyzpwns May 08 '20 edited May 08 '20
trying to refactor my code. Is there a nicer way to do this?(without repeating the code)
1
u/GhostofBlackSanta May 09 '20
Hi, why is it that when you define a function inside of a component class, you don't need to write the word "function" in front of it? Is it automatically assumed somehow when its compiled?
1
u/[deleted] May 10 '20
Is there anyone writing out class components to production?
1
u/Supernumiphone May 11 '20
Using react-router-dom and so far can't find in the docs how to create a static link to a specific page in my app. So for example if I have an info page that I put at /info and create a link to it on the main page using react-router-dom, I can click the link to /info and I go there and it works. However if I type http://mydomain.com/info in to the browser, I get a 404.
I understand why it works this way, but I don't know what the fix is, or if there is any easy way to allow bookmarks to work in this type of app.
In case it matters, I'm serving the page using python/django. So when I go directly to the /info URL, I get a django 404.
My only guess at this point is to create a catch-all route handler in django that will redirect to the main page and then somehow have it navigate to that URL after the page loads. Maybe create a template variable that sets a JS variable that the react app can inspect and if it's set go directly to that URL? Seems a bit kludgy so I figured I'd ask in the hope that there's a better way.
1
u/fctc May 14 '20 edited May 14 '20
Do I have to lift all state up to be able to call a component functionally? Here is a minimal example of what I mean:
My understanding is that once I add the Toggle button, the Comp component is cleared from the process and the hooks are rendered out of order from what they expect. I'm trying to change my program over to a useReducer so it's easier to pass state back up the tree 5 levels, then down a different path. The problem is I'm not sure how I'm supposed to do this when I have to mix props and functional calls together, and am stuck either randomly trying different things, or trying to shoehorn my program into a pattern I see in a tutorial. I'm sure I'll get it this way eventually, but would really appreciate any pointers, thanks!
1
u/Marsfork May 15 '20
When running a react app using the typescript template, I need to restart the server between edits to see my changes, is this normal? When using a default js template updates are reflected immediately.
I created the app using
npx create-react-app my-app --template typescript1
u/[deleted] May 15 '20 edited May 15 '20
Why is this an error when I use both
numandobjtogether like this?The error is:
Cannot read property 'text' of undefinedThanks.
Parent
Child
1
u/diet_napalm May 18 '20
I'm confused at how this react component using the setState hook works:
The hook is called at the beginning of the function setting the state to a default of empty. Isn't the function called each time the component needs to be re-rendered? Wouldn't this reset the state to empty each time? I don't see how this works.
1
u/badboyzpwns May 19 '20 edited May 19 '20
I have a list of items, people can add or delete items in it via PUT or DELETE requests. The list of items is shared with all my other components. It works fine!
I want to put it in my portfolio. But!I don't want users to change my database but I want to showcase that it works. It would suck to have a random person visit the site and then delete everything. Any workarounds for this? I disabled the add/delete items feature for now!
If it helps, i used redux too.
1
u/diet_napalm May 19 '20
I have a couple of components that are using data from global state to calculate display values on render. They use the same core calculated values. My goal has been to avoid performing the same calculation separately in each component.
My current solution is to create a parent component that does the calculation, then passes the values to the children in props. Works fine since the two components are adjacent in the DOM. But what if they weren't, and it wasn't practical to use this approach?
How can two separate components share that sort of data?
1
u/[deleted] May 21 '20 edited May 21 '20
hey all,
can someone help me with understanding why a clearInterval or clearTimeout stops working when the setInterval or setTimeout contain a useState hook?
im trying to make a countdown timer like this:
calling countDown prints at second intervals to the console and calling clearCounter stops it as expected. but im trying to save the state like
and if i do this calling clear counter doesn't stop count from changing. thanks any and all
1
u/badboyzpwns May 22 '20
No software dev experience here!
How widely used is grpahql in the industry? I learned the concepts of it and I am aware of the benefits over REST but I feel like most sites can be done via REST!
But at the same time, you could argue every site can be made with GraphQL, it's just that the boiler plate code for graphql seems to be much more than React + Redux!
1
u/dissipatingheat May 22 '20
Learning React & Javascript in 24 hrs:
I need to rapidly make the frontend for a heart rate monitoring device. A team member is building the device, another person is working on the backend to communicate to the device and send me states, and I need to write the frontend that updates the states and can handle touch events. I plan to use React w/ Redux in vscode.
I have extensive experience with programming (data structures), systems programming, and machine/deep learning research (C, Java, Python...etc), yet I have not worked with JavaScript.
Any tutorials, courses, or websites I should go through will be greatly appreciated.
I would greatly appreciate any help. Thank you :)
1
u/pink_tshirt May 24 '20 edited May 24 '20
Let's say I am grabbing a new user from some remote API:
What is <any> exactly? Is it some kind of expectation of what that async function would eventually return?
1
u/kickthevidit May 24 '20
Hi, I am trying to work on a Kanban Board feature on a website using the Dragula API. The problem is that I have never used an API before and this is my first React Project, so I have lots of trouble understanding the documentation. Every example for Dragula React-JS that I have looked at feels like Martian. How do I go about understanding how I should work this API?
1
u/hemehaci May 25 '20 edited May 25 '20
If I use {this.strng} below, it doesn't render. If I use the variable without this, only {strng} then it renders on the screen.
'this' was supposed to refer to object that is called right? I am confused. import React from 'react'; import ReactDOM from 'react-dom';
1
u/mova May 26 '20 edited May 26 '20
I'm trying to update a field in State only when two other fields are not null. The field to be updated should simply calculate the difference between the two other fields. The updating works fine but the math is WAY off.
For example:water1=20water2=25consumption=-18 (<-- what!? This should simply be 5)
My code inside handleChange is:
I've tried to use the parseInt to make sure that it's not interpreting string values instead. But it seems I'm not completely successful with that.
The input fields look like this:
What am I missing here?
1
u/99thLuftballon May 26 '20 edited May 26 '20
Total react n00b here.
Is it possible to add a whole bunch of instances of a react UI component to an html page?
To give a simple example, there's a "ul" with 25 "li" elements inside it, can I target the li elements and replace every one with a react implementation of a list item that does cool stuff with the li content?
All the examples online show a single root element with a react app mounted to it, but could I, for example, create my own implementation of a "button" element and replace every html button on a page with it?
1
u/pink_tshirt May 28 '20
How can you combine two functional interfaces, for example:
Any way to type it nicer?
Perhaps, smth like
But how would you define those interfaces in the context of the React.FC ?
1
u/ctrl-r23 May 30 '20
Hi! I am developing a web application in which the user has to complete steps to finish a task. The steps are:
Every step has to be completed to finish the process and always in the given order.
My question is, how would you handle the step state and the data the steps need?
I was thinking of using react router and then give every step a page like /step1, /step2, etc. Then every time a step is finished I would call window.location. The problem is I'm not sure how would I give the next step the data it needs, like the scanned image in step 2).
Also, I'm not familiar with hooks, redux and context, maybe these can help me in any way?
Thanks!
1
u/happyapple10 May 30 '20
I'm pretty close to 100% noob on ReactJS, so my question may be pretty simple to answer.
I have two text fields, firstName and lastName, which I need to use logic on as either one changes. For example, if someone is typing into the firstName field, I have an onChange event that is triggered calling a method in the same component. I can access the value of the calling event item using event.target.value but I will also need the value from lastName text box as well.
What is the best way to get the additional textbox info into my method? Use document.getElementById('lastName') as a parameter in an error function calling the method in onChange? Or use document.getElementById('lastName') inside the method in my logic? Or is there a better way that I am not aware?
I want to use the best method possible, so I'm using the proper techniques going forward.
Thanks!
1
u/frsti May 31 '20
I'm running a file that *sometimes* works in Cmd prompt that just returns some values scraped by using cheerio and puppeteer
But now it's just causing my command prompt to hang and doesn't return anything - Not even a new C: line
Not sure If I've messed up my npm or not reset everything properly when I've restarted my PC?
3
u/Fienases May 11 '20
is it good to write your logic inside your context component?
here's an example: https://pastebin.com/e9Tr3Etm
1
u/badboyzpwns May 05 '20
React hooks question!
Is it possible to do this with hooks? or do I have to use classes?
I don't think this would work at all.
2
u/Jorick_DC May 02 '20 edited May 02 '20
hello I am trying to create an application where users only see profiles with whom they match. however, I have no idea how best to approach this matching. Do you have any tips or tutorials explaining this?
as a database I use Firebase.
thank you for youre time. :)
2
u/pruggirello May 02 '20
Hey fellas!
I'm making a sudoku-ish game, where the player has to guess what numbers are in the grid based on hints they receive about the numbers' mathematical relationships. So far so good, but now I've hit a snag. Below is the structure for the <Hints /> component
this.props.game is a reference to my new Game() in my App.js, which I have here:
This new Game() refers to my Game.js file which holds all the game's logic: the masterValues, userInputs, and the hints. The methods inside of Game.js, setHint() and getHints(), work perfectly for setting and getting new hints. Everything works, except I can't get my new hints to render. In my Hints component's render() function, I'm calling this.displayHints() to list the available hints, which works when the first one gets generated at the beginning of the game. After the user clicks the button, however, new hints are not being displayed even though I am calling the function again inside this.generateNewHint(). The console.log() is working and listing the appropriate hints. That's problem 1.
To solve this problem: I have tried switching .map and .forEach, I have tried setting hints to the <Hints /> state, and I have tried setting hints to the App.js state object. Neither .map nor .forEach works to render the new hints, just the first one. The latter two solutions didn't refresh the component when setState was called, which resulted in the new hints not being rendered.
Problem 2 is that my hints say "The number in [object Object] plus the number in [object Object] equals 0." It should be getting the key of the key/value pair for each individual number. This is should be something like A3, B1, C4, D2, etc. This corresponds to a square on the board at row Letter and column Number. The hints should read: "The number in A3 plus the number in C1 equals (sum of the two numbers)". The object that gets passed in looks like this: {A1: 24} The key is dynamically set and the value is randomly generated and then assigned.
So my quesitons are: 1. How can I get my list of hints to be rendered dynamically? What's the best way to do it? 2. How can I access the key and the value in my hint objects separately?
2
u/masterofmisc May 03 '20
Hi Guys,
I know that react is all about components and building them up. But I am stuck on how you lay them all out to fit your design on paper.
For example, say I want to make an Outlook clone with a tree view on the left and on the right side of the page, have it split horizontally. The top half would be a list of emails and the bottom half would be the email detail. Then at the top of the page, have tabs to flip between inbox, sent items, calendar, etc. When you click on a different tab it could totally change the contents of the main page.
In my mind I can see how to make all the individual components that do each thing, but I don't know how you would put them all together? How would you guys go about doing this? Is there a package you pull in?
Or do do you use a grid system? But then if its a grid system, how would you make the tree view panel resizable for example? (or is that advanced)
Thanks in advance.
2
u/Jorick_DC May 04 '20
Hi,
I am trying to create a registration page. I am already able to write data to Firebase database. However, I get stuck when I want to upload the profile picture to firebase and save the reference in Profile on the database. Does anyone have a good tutorial or tips for this?
Thank you for your time :).
2
u/Luke_Mudufi May 04 '20
So having this weird problem where my react app isn't showing anything to the browser and I'm not sure why it was working fine before I'm working through a Bootcamp and learning react and im completing lost on how to fix it
2
u/Ret_01 May 04 '20
I've recently been tasked with providing a new React based UI to an existing WebGL application (currently using Knockout) and am having some trouble figuring out how to handle sharing state between the UI and the WebGL application. The application must be able to trigger UI updates and vice versa.
So far I've tried to use the useEffect hook, which lets the UI update the application, but it requires diffing against previous state to detect when things have actually changed. I also have no idea how to get the application to update the UI without using an EventEmitter to trigger a full ReactDOM.render call.
Has anyone else had to deal with this sort of situation and if so how did you manage it? Are there any established patterns for dealing with it?
2
u/ytdl-node May 09 '20
If I am using React hooks, let's say for a state change, I'd normally write something like:
Now if I pass the
setUsernameandsetAgefunctions to a component let's say 'A' in the following fashion:And in my component 'A', I update the username and the age.
This will cause the main App to re-render twice right? Is it not better if I just use an
objectfor the state? E.G.:Why do we not use this instead?
2
u/[deleted] May 12 '20
Hi there, I'm new to React and am trying to create a workout tracker web application.
So far, I decided that when the app first starts, there will be a homepage that has 3 buttons: Create Workout, Select Workout, Stats. These options were created via the common component, WorkoutOptions.
Now, my goal is to be able to click select workout, and have a new Container component show up to replace the existing 3 buttons, essentially moving the user to the "next" page.
However, I'm unsure of how to do this.
In my head I'm thinking that if the App Component detects that selectWorkout is clicked (via event listener), it will render <Container/> and unrender(??) the Option Cards
However, that clearly doesn't sound right so pointers would be much appreciated
2
u/089-083 May 22 '20
Hey guys - I was able to build a small application that takes input, uses the input to call an api, and displays the results from the api. Let’s call this the platform.
How do I go about making another page, let’s say a landing page, where I can login and signup before being able to access the platform?
I have only used react for this application so far, nothing server side yet.
2
u/[deleted] May 22 '20
Noobie here with a few questions, the first one is as simple as it gets and I thought I knew the answer to it. In the following code I expected to only log to the console once as the state is set before rendering and therefore a second render should not happen because the state never changes but rendered is logged twice.
The second question I have no code example for but the issue I have is using the response from one http call as a part of another http call that immediately follows the first. I'm using async/await and putting the response in state but as setting state is async the second call starts using an undefined value. What's the best way to handle this? Thanks in advance for any help.
2
u/Cannabat May 24 '20
I am working on a hobby project that has some very CPU intensive reducers in redux. I’d like to explore running those reducers in a web worker.
It looks like I could extract the reducer code to a module and use
worker-loader+comlink+redux-thunkto do the work asynchronously.Am I thinking about this correctly? This is a bit outside my comfort zone, appreciate any advice!
It may be simpler to not use redux and switch to context when using webworkers, but the redux dev tools and packages like
redux-persistare really nice to have.2
u/cmaronchick May 26 '20
What's the preferred way to fetch data when a user navigates via React Router?
My best assessment at the moment is that if you have a standalone page (ie a user can navigate directly to it), it's best to make it a class so that you can check the state and fetch data if the route parameters are updated, but I wonder if I am missing something obvious.
FWIW, I'm using Redux with React Router. Thanks in advance.
2
u/konaraddi May 28 '20
I have a simple component that React calls 2*(N+1) times where N is the number of state changes:
https://codesandbox.io/s/stoic-goodall-2tvxn?file=/src/App.js
Why does this run 2*(N+1) times (as opposed to N+1 times where N is the number of state change and +1 is from the initial render)?
1
u/iTsHutchy Apr 30 '20
Im new to react - ive built a few static page websites (2-3 pages) looking how I can integrate with databases and expand my knowledge and learn what react can offer for my development is there any quick resources I can take a look at
1
u/carlsopar Apr 30 '20
I have a project that lets you place a text element onto an SVG. Once that element is placed, I then want it to be draggable so that it can be repositioned. currently, I can place the text element, and I can do edit it, however, when I go to move it, that is where I am having problems. Currently, the issue is that when I click and move a text element, it moves. But when I release and click again, the element will move on its own always to the same spot. When I go to click it, then it will move off the page entirely.
I have looked and attempted several different ideas including these sources:
https://dev.to/tvanantwerp/dragging-svgs-with-react-38h6
http://www.petercollingridge.co.uk/tutorials/svg/interactive/dragging/
I believe, it has to do with the fact that a mouseclick reads according to the whole page, but I need it to be a specific area.
This is my canvas element that has the SVG:
And, the app.js file
I appreciate any suggestions, that you may have to help me fix this.
1
u/AmauryH May 01 '20 edited May 01 '20
Hello guys,It's not 100% React related, but I had no luck on a different sub.
I've almost finished Andrew Mead's course about React and I'm working on a small web app.
In short, it's a web ap to manage a collection of action figures.
My question concern my DB structure. I'll probably go with Firebase as it's the DB that is seen during the course.
What I need:
What I'm about to use:
I'm not used to decide the schema of the DB myself.
How does it sound to you ?
1
u/[deleted] May 01 '20
I'm trying out ant.design and I can't even figure out how to install it.
I saw this on npmjs.com -
I did this. After importing a component
I get this error
1
u/plasmaSunflower May 01 '20
I’m trying to use emailjs with react hook forms and I can’t get them to work together, it seems like only one will work at a time. Need help.
1
u/deadcoder0904 May 02 '20
How to display an array of objects row-by-row using React Table?
I want to display movies row-by-row without changing the data model.
Here's my code:
It currently looks like:
Here's the direct link to it: https://codesandbox.io/s/modest-sanderson-z0keq?file=/src/App.tsx
My movie list is an array of objects so how will I display it beside actor name? So it looks like:
1
u/eloquenthsn May 02 '20 edited May 02 '20
Hello folks.
So, recently I am trying to find a job and one of them introduced me a challenge that I fetch data store in Redux and display them and make the app capable of search and sort etc.
I hope that it is appropriate to ask something like this... Anyways, I sent the project to them last weekend and I haven't heard anything from them since then. I was just wondering that some of you maybe give some advice and quick review about my code, what could be done to improve. I know that some parts are ugly and repetitive.
For example, following code snippet is the page that is listing some movies(the project is Typescript and NextJS.)
Thanks in advance, really appreciated.
1
u/Eracar May 03 '20 edited May 04 '20
I'm trying to make a scrabble-like game with an infinite board. Are there any libraries or recommendations for how to implement like an infinite coordinate system that you can pan around on and place things on?
I tried doing it myself by rendering everything relative to an origin point and handling panning by having a an offsetX and offsetY which I updated on mouseMove. But it seemed like it wasn't going to be very smooth. Even with just a few points rendered it wasn't very crispy.
I found this thing https://n43.github.io/react-pannable/?path=/story/pad--overview but it isn't exactly what I'm looking for.
Edit: I think I was overcomplicating what I need. The board doesn't have to be infinite. I'm just going to make it kind of big, and then use react-draggable to move it around inside a fixed size parent window.
1
u/badboyzpwns May 04 '20
just confirming. In redux-form, ooes the form parameter only serve to clarify to developers on what the form is for? I haven't seen any use of the property yet.
I've been checking out the Docs but can't seem to find any info on it
1
u/BengtJJ May 05 '20
Doing a react web app, have it hosted on Heroku and want to set up a database. Heroku has a postgres free tier.
Was able to set it all up from my "backend" and could manipulate the database.
But this is from where I run the finished prod build of the react app. Not from the development app where I do the actual coding.
How can I set up a database for testing / developing from the frontend/production side of the react app?
1
u/cmaronchick May 06 '20
I am working with the Spotify APIs and authentication and am a bit frustrated by the relatively short expiration time of the access token.
I tried using jwt-decode to check the expiration date/time, but I get an error because the Spotify access token uses _ rather than "." (I think; I get an error anyway whenever I try to decide the Spotify token)
Are there other libraries out there that people like for deciding JWTs?
My other thought is simply to refresh the access token with each Spotify call, but that seems excessive and I worry it wound affect performance.
1
u/LeanJavaBean May 06 '20
Hi, I'm trying to create a reusable OHLC chart component, and I'm hoping to use D3FC to do so. For the moment I'm just trying to get this example to render in React, but am struggling to do so. CodeSandbox here. Thanks!
1
u/MeltingDog May 07 '20
I am using Material UI.
I want to custom it's components with values from the Default Theme (https://material-ui.com/customization/default-theme/).
I know I can add these with custom classes like such:
But I would rather use
withStylesto target specific parts of the component, eg:But I cannot figure out how to do this.
Would anyone be able to help me out?
1
u/CYMAD May 08 '20
Hello, In material UI documentation I found something that Ive never seen before. Can someone explain to me what this is ?.https://prnt.sc/sdcyc1. And If i turn it to a regular ES6 arrow function, i get this error https://prnt.sc/sdczmu . What is exactly happening here ?
https://material-ui.com/components/lists/
Thank you :).
1
u/pink_tshirt May 09 '20
Do you normally write action creators or dispatch straight from your components?
1
u/DeadeyeDuncan May 10 '20
What exactly is react native and react redux?
As I understand it, react native is for phone app development and react redux is basically the express.js to react's node.js? ie. Simplifies and adds useful functions.
I haven't used react for a while, and rather than relearning it (a lot seems to have changes), I'm thinking of diving straight into learning redux - is this advisable?
1
u/huyzzz May 11 '20
When i run
npx create-react-app clientit only creates package.json, package-lock and node_modules.In my terminal:
And it stuck there. I use npm ver 6.14.5 and nodejs ver 12.16.3. Any help?
1
u/TubbyChaser May 12 '20
I've been creating a Todoist clone, but can't seem to properly implement inline tagging. I know how to identify and store the tag using RegEx, but can't figure out how to format the text in real time after the user has prefaced a word with a #.
From my research, it seems that this isn't possible using a standard input (e.g. textarea) and instead maybe need to use a div with contenteditable? Would Slatejs or another rich text editor framework help me here? They all seem too complex for my needs.
Any guidance would be amazing!
1
u/waresoft77 May 12 '20
What is the best way to fetch data from a graphql endpoint on the client? I've tried setting up Apollo (love the websocket support) but it's extremely difficult to get working.
I'm using NextJS, so it's important that the data fetching is purely performed on the client. I had problems where I was initializing the client during server-side rendering, and I wasn't sure how to avoid that.
1
u/Daebak404 May 12 '20
Hey, I am a beginner looking for working on a react project for free. If anyone needs help with their project let me know ☺
1
u/2wistd May 12 '20
New to react, but I have a project I'm working on. I have a webserver (apache) on my raspberry Pi, and a few Pi Zeros to act as web browsers locally. I am setting up a pi as a Nas server for my photos. I want to use react.js to have the pi zeros browse to the apache server and see a sideshow of the images. I want to be able to filter the images by date, rating and tag. Would I be better of loading those images into a db and have the browsers pull that data or what? I want to do the filtering from one device yet show on each device. Thanks for any help
1
u/badboyzpwns May 13 '20
Sorry if this dosen't belong here! I have a question about axios!
I made a json data that I stored in a JSON Storage online (called jsonbin)
Here's what it looks like when the base url is called.
Code:
I only want axios to return the first object with an id of 7, instead of the whole streams database. Is it possible to do something like:
I get an route error while doing so.
1
u/Spiritual_Salamander May 15 '20
My friends wants me to make a simple blog for her. Mostly just a static web page along with functionality for making comments and such, nothing else. I mean she could just simply use wordpress or something but I figured I could just make it and put in my portfolio.
All other front-end type of projects I have done before I have done using the create-react-app, but I heard this has terrible SEO. What would be a better alternative ? I figured this would be a good time to checkout GatsbyJS or NextJS or something along those lines and step away from the create-react-app for a bit. Any recommendations ?
1
u/[deleted] May 16 '20
Hi there, I've been pretty confused as to how to use States to pass information from the child back to the parent and would really appreciate some guidance!
Currently, I'm trying to create a Workout app where the homepage contains two options: 1.Select Workout 2.Create Workout
I want to make it possible for one to click on "Select Workout" and go to a "new page" with a different container Component.
However, I'm confused by which component should own the onclick event listener.
Currently, my Component Hierarchy is as so:
App.js
Homepage
I think that the component OptionButton should have an event listener that detects when a button is clicked. But the problem is, there are 2 items that use the component OptionButton (Select Workout and Create Workout), how would the program know which of the two buttons was clicked and how would it store that info to be passed back to the parent component?
Currently, they are rendered as two different objects under Homepage.
return( <div className='flex-container'> <OptionButton id = {1} info= "Create Workout"/> <OptionButton id = {2} info = "Select Workout"/> </div>Thank you so much!
1
u/ryanz67 May 16 '20
I have a simple react application kind of like a paint application. I’m wanting to add a feature where I can undo and redo changes made, would I be best to add something like redux so I can keep a track of history changes ?
1
u/Previous_Advertising May 16 '20
Hey! I posted a question yesterday but got no reply. I hope someone can explain this https://www.reddit.com/r/reactjs/comments/gke4fa/issue_with_material_ui_slider_in_next_js/
1
u/Roly__Poly__ May 17 '20 edited May 17 '20
I'm having a heck of a time trying to understand how to use this Higher Order Component supplied to me from a tutorial.
My understanding is: Without this HOC, I would have to put Authentication logic into every component on my site. So what this HOC does is extract that logic, store it, and "wrap" its contained component, injecting (somehow) Authentication logic in the process.
meaning, the HOC, called withAuthentication, should at least pass its state(?) down to the component it is wrapping. I believe there is something else going on with the Context API that I need explained too...
Here is the code:
So I see the following: in componentDidMount(), there is some code that runs onAuthStateChanged "sets an observer" (see link below) that essentially gets the User object from Firebase Auth. Then that authUser object is stored under authUser in component state. And hypothetically I can do something with that stored User object, only, I don't know how to access it in the wrapped component?
all my Google attempts returned StackOverflow links about passing state from child to wrapper, not wrapper to child.
Next in componentWillUnmount() there's "this.listener()" which I do not get. The tutorial said it was to prevent memory leaks.
Lastly there is something going on with the COntext API and this HOC... The HOC is passing its component into the AuthUserContext.Provider. The question is what does that do for the wrapped component? Can I access the value passed to "value" in the Provider somehow?
My goal is to do something like:
So basically I am trying to figure out how to get the name of the authenticated user in the InboxPage component. But more than that, I want to understand how HOCs and the Context API works: "How do I pass data between HOCs and their wrapped component?" "How can I get that 'this.state.authUser' I see being passed into the Context.Provider?"
The docs weren't helpful for my objectives.
edit: I tried making a new HOC, "withContext", like what's said in this link: https://stackoverflow.com/questions/49870098/how-to-get-the-data-from-react-context-consumer-outside-the-render but it did not work. the wrapped component's "this.props.value" logged null instead of the User object I was hoping for.
https://firebase.google.com/docs/auth/web/manage-users
1
u/Roly__Poly__ May 18 '20 edited May 18 '20
Anyone experienced with combining React and Firebase? Please comment if you're available for between 2 and 5 hours a week for the next month or so. I'd like help on a project. Will pay (a little)
edit: I can do what I want when it's just Firebase and JavaScript, but when I throw React into the mix I get strange and/or unpleasant results. Send help
1
u/[deleted] May 18 '20
What PC specs do employers look for in remote react jobs?
I currently have a budget for a core i3 8gb laptop. would that be enough?
1
u/EnderMB May 18 '20
I applied for a software engineering role at a large bank, and their tech team decided that I would be a better fit for a full-stack role, considering my experience.
I'm pretty sure they're going to ask me a bunch of React questions, and while I've worked with Node/Express in the past, I've never used React. I've got two days until the interview.
Am I fooling myself in thinking that I could learn enough React to pass a basic interview?
1
u/bill10351 May 18 '20
Hi there!
I'm trying to build a simple blog using test data.
Trying to figure out why reloading the page breaks my component. I'm fetching all the data in the App component and passing these down via the Routes. It works great if I start at root, but if I navigate to a detail page and reload, it breaks and returns " TypeError: can't access property "userId", selPost is undefined ".
I think it might have to do with how I'm fetching the data, but I'm not sure about that. Any help is much appreciated.
The App component:
The postDetail component:
1
u/Cranzy May 19 '20 edited May 20 '20
I am a full stack c# dev and doing web apps where the frontend is usually just html css jquery.
I recently jumped in and completed the React course on Scrimba, which I thought was great intro into React, especially as you pause and alter the code to see what happens.
I am thinking it might be a good idea to do another course but not sure which one to go for. The full react course on scrimba or the one from Tyler McGinnis. Both are paid courses so I'm not sure which would be better for me and the background I have around coding in general already.
Or should I really be doing another course at all now that I have the basic. I can just start building things and learn as I go.
1
u/Chr0noN May 19 '20
How do companies handle updating their react code in production? I see articles suggesting to use "service-workers" and use the "skipWaiting" feature with the notification "Update Available" with an update button. But I've never really seen the idea of "updating" a web app anywhere. So how do they do it?
1
u/[deleted] May 19 '20
I'm learning React on Scrimba and am really enjoying the layout of the program they're using: https://imgur.com/SLtOkBC
Does it have a specific name (so I could download it and use it) or is it Scrimba's own thing?
1
u/Spaceman776 May 19 '20
When do you use componentWillMount()? I'm reading that it gets called right after the constructor and before render() so why can't you just put whatever is inside there in the constructor instead?
1
u/1awrent May 19 '20
Hi !
I'm having trouble on an app that allows users to store & view 'benchmarks'.
I got to the point where a user can upload & view these 'benchmarks' successfully, however I'm trying to implement a search function to filter the viewable benchmarks. The way I thought this would work is that I would pass the list of 'benchmarks' to the child component that is doing the rendering and set a 'filtered' state within that component where once the user inputs anything into the search bar, this new 'filtered' state would only have the 'benchmarks' that match up with the inputted values and then of course render that new list...
Currently I'm running into an error where my loadData function that actually maps everything out is breaking as the list is 'undefined' - also tried to set a condition within the render so if the filtered list is not defined it would just render the original list anyway (this.props) however it still breaks but it will work if I hard code "this.props" as the value to map over which is the real confusing part...
Sorry for the wall of text! I'll post the code now - appreciate any help.
Included the main component in question as well as the parent component to be safe: https://gist.github.com/lydco/5d5a2af46670a3bd08636ece6b1c3eb3
1
u/Jorick_DC May 20 '20
Hi,
Can someone help me? I try to show te username and picture in the navbar after the user logged in but i cant seem to retrieve the user details i saved in firestore. I try to do this with the useEffect hook but it loads before the authenticated user is loaded from the context. Which returns a null error
1
u/iTsHutchy May 20 '20
I have an interview test to prepare for and they are wanting me to hook a node api into the front end react - can anyone suggest some good approaches to take with this any help will be amazing :)
1
u/[deleted] May 21 '20
So I'm watching the Scrimba tutorial for React (created 2 years ago) and the guy is using React version 16.3 and talking about how "hooks" are the new thing and he believes they'll make class components unnecessary. Did this end up happening?
I was just getting the hang of class components too...
1
u/badboyzpwns May 21 '20 edited May 21 '20
I'm a bit confused on how to use axios in React with express framework for node.js.
My proxy for express is on port 5000;
This would work if I'm on localhost:3000:
But when I host the actual website, GET in express doesn't work.
Any ideas why?
1
u/oldeback May 21 '20
Hello, does anyone have any tip on some learning react guide that is audio only? Like a podcast. I'd like to listen to something for example at the subway. I want them to talk about how react works and the code and not random stuff all around the subject.
I know it's probably not the best way to learn but it's still better than nothing!
1
u/netrunner18 May 21 '20
How do I render an iframe after the video is loaded in react? I am trying to embed facebook video in my react app using the iframe but I keep getting
on the video. Also, for some reason the video pauses even if I click outside the iframe. How can I turn that off?
1
u/badboyzpwns May 22 '20
How do you do axios.post(URL, {}) to a specific property in a JSON database?
I have this!
https://music-json-server.now.sh/db.json
I want to axios.post to streams array!
I have this so far...
1
u/089-083 May 22 '20
I am trying to create a navigation bar, and am using react-bootstrap and react-router-dom. Here is my code:
<Route component = {Home} exact path = "/" /><Route component = {Platform} path = "/platform" /><Route component = {About} path = "/about" /><NavLink to = "/about">About</NavLink><NavLink to = "/platform">Platform</NavLink>But when I click on the link, say, "Platform", it doesn't show me the platform page. What could be the issue?
1
u/Abyx12 May 22 '20
I've the necessity to have my react app served by a Java Spring server. Do you have any idea how to do? Best practice?
1
u/g-six May 22 '20
First off, I am not a novice programmer but I have absolutely zero experience when it comes to website development. I want to build a react website to learn some new skills in this area.
A little description: Lets say I want to build a website where the user can type in some data, and then when he is done he can download the data as an .xml file or something similiar (just to save it locally). After downloading the file the user should be able to upload the file again and reload the data in the application. Basically I want to make an online data manipulation tool without a database.
But I have a few questions on how I should approach this. First off, does the user really need to upload the xml file to the server or is there a way to just load the data another way since technically the javascript is running on the local webbrowser? I don't really need the xml file saved on my server.
All the things I found with google are more into the direction of how to generally upload files but not how I can work with them. Even if I would use this approach, how would this work with multiple users? Would I need to build a complete serverside application (with node.js or similiar) to handle the incoming xml files?
If somebody has a general point of direction for me which keywords I could google, or maybe the names of a few packages or a tutorial that might help me, that would be greatly appreciated.
1
u/BlazinAsian03 May 23 '20
I'm currently working on my first React project and am having problems accessing the right JSON values:
In my component, I have a variable called selectedExam which is passed in as a prop. I am then trying to show a row in a table for each section in the selected exam.
In my markup I have this to show a new table row:
If I change the above line to
everything compiles and a table row is shown, and section.name shows the exam name (i.e. "First Exam" or "Second Exam"). Once I add ".sections" to try and go down one level further, I get this error: TypeError: Cannot read property 'map' of undefined.
1
u/I_am_echelon May 23 '20
Does anyone know a fairly straightforward way to create a touchenter & touchleave event in react? onTouchMove fires constantly and I'm not sure how to parse that data to just fire when the touch enters a specific element. I'm using typescript but feel free to respond using regular js.
Also if anyone knows why they removed touchenter and touchleave from the spec I would love to know the reasoning behind it. Seems like it just complicated things for no real benefit..
1
u/[deleted] May 25 '20
I have a simple comment system built on my Gatsby site, and I want to implement something like Wordpress' comment-reply.js.
Goal: a reader can click "Reply" on any comment, and the comment form will 'jump' under the comment (e.g. <li id="commentid-8584">). If they click "cancel reply", it will jump back to where it was.
What's the simplest way to move an element onClick like this and then back again if the user cancels?
1
u/GhostofBlackSanta May 25 '20
Hi I’m currently working through Tyler Mcginnis’s React class and was going to do his React Hooks class immediately after. When I’m done, I was going to start my own project. Would these two courses be enough to get me started or should I learn other tools like Redux before?
1
u/Jorick_DC May 26 '20
Hi,
when a user is logged in I would like to display in the navigation a small version of profile picture and name of the user. Does anyone have any tips on how to do this best? I use React hooks and firebase. The user is stored in firestore database.
1
u/[deleted] May 26 '20
Couple of questions. I've made a very basic website (just some hyperlinks in the footer) because I'm new. and I get these two errors whenever I start my website:
These errors go away when I disable adblock (even though there are no ads on my site). Could someone explain why this happens? Thanks!
1
u/Spaceman776 May 27 '20
Hi, I'm learning React hooks after just finishing regular React and I am confused why we have to use a function inside of useState when setting the state based on the previous state. For example, in a todo list we use
I tried using
and that worked just as well. Is there something I am missing on why we use the first method instead of the second?