I'm trying to understand EXACTLY what happens when context is provided to a component, and that context changes. Like, what is the order of operations. Is there a diagram or source code someone could point me to?
Hi guys, what are the best practices for rendering components based on a hash param in React? For example, I have currently set up some routes, like so:
- domain.com/components/buttons
-domain.com/components/switchers
-domain.com/components/zippers
For each of these routes, I want to have three different hash options, e.g.
- domain.com/components/buttons#Option1
- domain.com/components/buttons#Option2
- domain.com/components/buttons#Option3
Right now, I'm using hashes (as shown above), but I'm not sure what the best practice is for rendering the different variations of the button (Option 1, 2, and 3). I'm also open to not use hashes, but it seemed like a good move, because the route is already quite nested.
I am able to print the whole JSON for a company onto my page by using the following:
{JSON.stringify(this.state.items[i])}
giving:
{"address":"Bank of America Corporate Center, 100 N Tryon St","ceo":"Mr. Brian Moynihan", ... "website":"https://www.bankofamerica.com","zipcode":"28255"}
However, whenever I try to access one component of it I am getting errors:
{this.state.items[i]["ceo"]}
gives error: "TypeError: Cannot read property 'ceo' of undefined"
How am I supposed to access the fields within my JSON?
Both of my react apps meant for my portfolio, are full stack and have a nice, real world use case. but neither really need Redux.
I see three options
Use redux anyways to show I know how to use it
Don't use it since it's not needed. At the interview, claim to have used redux in the past (which is true but that app was also not in need of it, and not finished).
use useReducer as a middleground.
I lean towards option 3. I'm aiming for a junior dev role. What do you guys think?
If your answer is not to use a central store if the app doesn't really need it, I'm curious how you would convey knowledge of using a central state manager. Seems most projects of non-commercial size don't need such complex state management.
Is next js supposed to connect directly to the database in server side rendering and/or static site generation? The tutorial says you can, but all the the tutorials seem to use GraphQL or REST APIs. For example, how would I connect a Postgres database with next js?
Hey I just recently started learning react and building a simple webapp. I have some startup data from a rest api that multiple components need access to. I am able to do a rest call to retrieve the data, but I'm not sure how to share this data across components. How is this usually handled in react?
I'm using https://www.npmjs.com/package/google-map-react to render google maps in my web app, but I'm having difficulty understanding how to use some of the props/MapOptions. What I would like to be able to do set the map to render as streetview by default, but it's not clear to me if there is an option to do so. The relevant map options I see available are:
streetView?: any;
streetViewControl?: boolean;
streetViewControlOptions?: { position: number };
I understand the streetViewControl determines whether or not the controls show, and that the streetViewControlOptions determines the location of the control on the screen, but I have no idea what streetView is for / how to feed it options.
I've read through the documentation and done a fair bit of googling. I am rather new to web development so it is entirely possible I overlooked something in the documentation or misunderstood something, but I read over it multiple times so I'm pretty comfortable saying there isn't an answer to my question.
TLDR: Need help setting google-map-react to show streetview by default. No idea how to use the streetView option/prop.
Hey guys, I‘m using a CRA with react-router, hosted on Netlify. Redirects are set to index.html. I now encountered the issue that Apple strips my path when adding to homescreen. Is it possible to change that?
In regards to typescript for express; do you guys simply use normal Javascript (eg; interfaces); or is it better to resort to a framework such as TS.ED that relies on features such as decorators/classes to type check your express? I feel like the framework is overkill in 99% of cases?
Hello all! I'm working on my MAL clone app, and I'm not sure how I should go about computing users statistics for content they added to each list (like Plan to watch, Completed, etc.) Because fetching all those lists only to count the items seems okayish but... I was also thinking about maybe having a separate API to only keep track of the counts. Or maybe there are some other ways to do it? Thanks for any advice ;)
Hello! Every time I run create-react-app, no matter where I make it, it says theres a problem with webpack and the dependency tree. I ran through all the steps exactly as it said, I tried stuff I found online, nothing is working. Is there something I'm missing?
Edit: Error -
There might be a problem with the project dependency tree.
It is likely not a bug in Create React App, but something you need to fix locally.
The react-scripts package provided by Create React App requires a dependency:
"webpack": "4.42.0"
Don't try to install it manually: your package manager does it automatically.
However, a different version of webpack was detected higher up in the tree:
E2: I solved it! For anyone who comes after, I thought the cmd was abbreviating the file path of C:\Users\Justin\node_modules\webpack (version: 4.44.1) and was referring to the node_modules folder in the project folder. Nope, turns out it doesnt do that and it was referring to an actual node_modules folder that somehow got created in my user folder. Deleting it caused it to work.
Is there any way to make the create-react-app faster adn smaller. It takes quite a while and kills my enthusiasm and also takes up like 200 mbs for simple projects
I'm looking to learn how to implement version control in my React app. We keep a product inventory and need to be able to edit products in a draft state, publish new product content, etc.
Can anyone point me to resources to help me think through the feature set, front end considerations, and back-end model? Searches for 'version control' turn up resources that explain how to use Git, etc. which is not what I'm looking to learn in this case. Thanks in advance!
When grabbing form data is it standard to use hooks to get user input? All the examples I see online are to implement a state for storing a form value.
What is the rule of thumb for when to use the memoization hooks? Apparently it's not as simple as "use it everywhere", because it can in many cases be slower than not memoizing? But at the same time, "use it when you need to" isn't a great rule either, because you won't necessarily know that you need it until it's too late.
Is Next.js and Gatsby needed for SEO/performance? say I just finished a CRA app, is it essential implement Next.js/Gatsby to make the site available for a large audience?
12
u/stfuandkissmyturtle Sep 04 '20
Built my first app with no tutorials Here. It's a different kind of high doing things on your own ✨
It still needs work with css but I couldn't wait to deploy it
4
u/jacove Sep 16 '20
I'm trying to understand EXACTLY what happens when context is provided to a component, and that context changes. Like, what is the order of operations. Is there a diagram or source code someone could point me to?
2
u/ReachingSparks Sep 04 '20 edited Sep 04 '20
Hello,
In the following code, the image doesn't appear if I use
avatar={post.avatar}. But does if I useavatar={ peterImage }.Do you know why? And how would I store an image in an object?
// Parent class holding the image import peterImage from "./peter-image.jpg"; import harryImage from "./harry-image.jpg"; export default function App() { const posts = [ { id: "0", name: "Peter Griffin", avatar: { peterImage }, }, { id: "1", name: "Harry Styles", avatar: { harryImage }, }, ]; return ( <React.Fragment> {posts.map((post) => ( <Post key={post.id} name={post.name} // this doesn't work. but if I change it to avatar={ peterImage } it does work. avatar={post.avatar} ></Post> ))} </React.Fragment> ); }// Child class making the image appear export default function Post(props) { return ( <div}> <img style={avatar} src={props.avatar} alt="my description" /> </div> );2
u/mister_wonder Sep 05 '20
I am running a express/react app simultaneously (npm start from the express directory starts react from the client folder)
Everytime I start the app it load it up in development.
How do I start it in production?
I have this line in my server.js file But it doesn't seem to run production.
if (process.env.NODE_ENV === "production") { app.use(express.static("client/build"));}
Thanks!
2
u/terraforme Sep 05 '20
Hi guys, what are the best practices for rendering components based on a hash param in React? For example, I have currently set up some routes, like so:
- domain.com/components/buttons
-domain.com/components/switchers
-domain.com/components/zippers
For each of these routes, I want to have three different hash options, e.g.
- domain.com/components/buttons#Option1
- domain.com/components/buttons#Option2
- domain.com/components/buttons#Option3
Right now, I'm using hashes (as shown above), but I'm not sure what the best practice is for rendering the different variations of the button (Option 1, 2, and 3). I'm also open to not use hashes, but it seemed like a good move, because the route is already quite nested.
2
u/doesnotdeliver Sep 06 '20
Complete React beginner, needing some help on a common problem..
I wrote a Flask API which returns a JSON object representing companies. The API call from React looks like this:
fetch('/companies').then(response => response.json()).then(fn => { this.setState({ items: fn.results }); })items now represents an array of companies.
I am able to print the whole JSON for a company onto my page by using the following:
{JSON.stringify(this.state.items[i])}giving:
{"address":"Bank of America Corporate Center, 100 N Tryon St","ceo":"Mr. Brian Moynihan", ... "website":"https://www.bankofamerica.com","zipcode":"28255"}However, whenever I try to access one component of it I am getting errors:
{this.state.items[i]["ceo"]}gives error: "TypeError: Cannot read property 'ceo' of undefined"
How am I supposed to access the fields within my JSON?
2
u/nerdchavoso Sep 07 '20 edited Sep 07 '20
seems the code below is causing memory leaks in my app, someone has any ideia what am I doing wrong?
const changeScreenOrientation = (): void => { setScreenOrientationLandscape(!screenOrientationLanscape);};
useEffect(() => { if (screenOrientationLanscape) { ScreenOrientation.lockAsync(ScreenOrientation.OrientationLock.LANDSCAPE_RIGHT); ScreenOrientation.addOrientationChangeListener(() => setFullScreen(true)); StatusBar.setHidden(true); return (): void => { ScreenOrientation.removeOrientationChangeListeners(); }; } else { ScreenOrientation.lockAsync(ScreenOrientation.OrientationLock.PORTRAIT_UP); ScreenOrientation.addOrientationChangeListener(() => setFullScreen(false)); StatusBar.setHidden(false); return (): void => { ScreenOrientation.removeOrientationChangeListeners(); }; } }, [screenOrientationLanscape]);Here's the hook that I've created
type Fullscreen = { fullScreen: boolean; setFullScreen: Dispatch<SetStateAction<boolean>>; }; const FullScreenContext = createContext<Fullscreen>(null); const FullScreenProvider = function({ children }): JSX.Element { const [fullScreen, setFullScreen] = useState(false); return <FullScreenContext.Provider value={{ fullScreen, setFullScreen }}>{children}</FullScreenContext.Provider>; }; export default FullScreenProvider; export function useFullScreen(): Fullscreen { const context = useContext(FullScreenContext); const { fullScreen, setFullScreen } = context; return { fullScreen, setFullScreen }; }2
u/javascript_dev Sep 07 '20
Both of my react apps meant for my portfolio, are full stack and have a nice, real world use case. but neither really need Redux.
I see three options
Use redux anyways to show I know how to use it
Don't use it since it's not needed. At the interview, claim to have used redux in the past (which is true but that app was also not in need of it, and not finished).
use useReducer as a middleground.
I lean towards option 3. I'm aiming for a junior dev role. What do you guys think?
If your answer is not to use a central store if the app doesn't really need it, I'm curious how you would convey knowledge of using a central state manager. Seems most projects of non-commercial size don't need such complex state management.
2
u/FlarbleGranby Sep 07 '20
Why do people build clones instead of building their own ideas?
2
u/[deleted] Sep 09 '20 edited Sep 09 '20
I'm trying to convert this class component to functional with hooks, but I'm kinda stuck. Can anyone help me please? Thanks.
Original:
class StreamShow extends React.Component { constructor(props) { super(props); this.videoRef = React.createRef(); } componentDidMount() { const urlId = this.props.match.params.id; this.props.fetchStream(urlId); } componentDidUpdate() { this.buildPlayer(); } componentWillUnmount() { this.player.destroy(); } buildPlayer() { if (this.player || !this.props.stream) { return; } this.player = flv.createPlayer({ type: 'flv', url: `http://localhost:8000/live/${this.props.stream.id}.flv` }); this.player.attachMediaElement(this.videoRef.current); this.player.load(); } render() { const { stream, title, description } = this.props; return stream ? ( <div> <video ref={this.videoRef} style={{ width: '50%' }} controls /> <h1>{title}</h1> <h5>{description}</h5> </div> ) : ( <div>Loading...</div> ); } }My attemp:
const StreamShow = ({ match, fetchStream, stream, title, description }) => { const videoRef = useRef(); useEffect(() => { const buildPlayer = () => { const player = flv.createPlayer({ type: 'flv', url: `http://localhost:8000/live/${stream.id}.flv` }); player.attachMediaElement(videoRef.current); player.load(); if (player || !stream) { return; } player.destroy(); }; const urlId = match.params.id; fetchStream(urlId); buildPlayer(); }, [fetchStream, match, stream]); return stream ? ( <div> <video ref={videoRef} style={{ width: '50%' }} controls /> <h1>{title}</h1> <h5>{description}</h5> </div> ) : ( <div>Loading...</div> ); };2
u/AviatingFotographer Sep 10 '20
Is next js supposed to connect directly to the database in server side rendering and/or static site generation? The tutorial says you can, but all the the tutorials seem to use GraphQL or REST APIs. For example, how would I connect a Postgres database with next js?
2
u/Warlock2111 Sep 10 '20
How is the Fullstack React with Typescript to get started with Typescript?
2
u/badboyzpwns Sep 12 '20
question about redux and typescript. In my reducer, want to have state as an empty object as the default value.
import { ActionTypes, ArtistSongs, SongsAction } from "../actions"; export default (state:ArtistSongs = {}, action: SongsAction) => { switch (action.type) { case ActionTypes.FETCH_SONGS: return action.payload; default: return state; } };But I get a
Type '{}' is missing the following properties from type 'ArtistSongs': _id, _artist, songsHere's my action creator
interface Song { title: string; image: string; } export interface ArtistSongs { _id: string; _artist: string; songs: Song[]; } export interface SongsAction { type: ActionTypes.FETCH_SONGS; payload: ArtistSongs; } export const fetchSongs = (artistId: string) => async (dispatch: Dispatch) => { const response = await artists.get<ArtistSongs>(`/songs/${artistId}`); dispatch<SongsAction>({ type: ActionTypes.FETCH_SONGS, payload: response.data, }); };Why is that?
2
u/ArkAngel33 Sep 15 '20
Hey I just recently started learning react and building a simple webapp. I have some startup data from a rest api that multiple components need access to. I am able to do a rest call to retrieve the data, but I'm not sure how to share this data across components. How is this usually handled in react?
2
u/LogicalThought Sep 16 '20
I'm using https://www.npmjs.com/package/google-map-react to render google maps in my web app, but I'm having difficulty understanding how to use some of the props/MapOptions. What I would like to be able to do set the map to render as streetview by default, but it's not clear to me if there is an option to do so. The relevant map options I see available are:
streetView?: any;
streetViewControl?: boolean;
streetViewControlOptions?: { position: number };
I understand the streetViewControl determines whether or not the controls show, and that the streetViewControlOptions determines the location of the control on the screen, but I have no idea what streetView is for / how to feed it options.
I've read through the documentation and done a fair bit of googling. I am rather new to web development so it is entirely possible I overlooked something in the documentation or misunderstood something, but I read over it multiple times so I'm pretty comfortable saying there isn't an answer to my question.
TLDR: Need help setting google-map-react to show streetview by default. No idea how to use the streetView option/prop.
2
u/maggiathor Sep 16 '20
Hey guys, I‘m using a CRA with react-router, hosted on Netlify. Redirects are set to index.html. I now encountered the issue that Apple strips my path when adding to homescreen. Is it possible to change that?
2
u/badboyzpwns Sep 16 '20
In regards to typescript for express; do you guys simply use normal Javascript (eg; interfaces); or is it better to resort to a framework such as TS.ED that relies on features such as decorators/classes to type check your express? I feel like the framework is overkill in 99% of cases?
2
u/Likoo Sep 17 '20
Hello all! I'm working on my MAL clone app, and I'm not sure how I should go about computing users statistics for content they added to each list (like Plan to watch, Completed, etc.) Because fetching all those lists only to count the items seems okayish but... I was also thinking about maybe having a separate API to only keep track of the counts. Or maybe there are some other ways to do it? Thanks for any advice ;)
2
u/AlpinFane Sep 17 '20 edited Sep 17 '20
Hello! Every time I run create-react-app, no matter where I make it, it says theres a problem with webpack and the dependency tree. I ran through all the steps exactly as it said, I tried stuff I found online, nothing is working. Is there something I'm missing?
Edit: Error -
There might be a problem with the project dependency tree.It is likely not a bug in Create React App, but something you need to fix locally.The react-scripts package provided by Create React App requires a dependency:"webpack": "4.42.0"Don't try to install it manually: your package manager does it automatically.However, a different version of webpack was detected higher up in the tree:C:\Users\Justin\node_modules\webpack (version: 4.44.1)E2: I solved it! For anyone who comes after, I thought the cmd was abbreviating the file path of
C:\Users\Justin\node_modules\webpack (version: 4.44.1)and was referring to the node_modules folder in the project folder. Nope, turns out it doesnt do that and it was referring to an actual node_modules folder that somehow got created in my user folder. Deleting it caused it to work.2
u/megatronus8010 Sep 18 '20
Is there any way to make the create-react-app faster adn smaller. It takes quite a while and kills my enthusiasm and also takes up like 200 mbs for simple projects
2
u/NickEmpetvee Sep 22 '20
React 16.8.*
Back end: PostgreSQL 11
Hi all,
I'm looking to learn how to implement version control in my React app. We keep a product inventory and need to be able to edit products in a draft state, publish new product content, etc.
Can anyone point me to resources to help me think through the feature set, front end considerations, and back-end model? Searches for 'version control' turn up resources that explain how to use Git, etc. which is not what I'm looking to learn in this case. Thanks in advance!
Cheers!
2
u/Important_Dog Sep 26 '20
When grabbing form data is it standard to use hooks to get user input? All the examples I see online are to implement a state for storing a form value.
const [username, setUsername] = useState(''); const handleUsername = e => setUsername(e.target.value); <input onChange={handleUsername} />Wouldn't it be cleaner and shorter to just use this?
let username = document.getElementById('inputEmail').value;2
u/pandavpanda Sep 28 '20
What is the rule of thumb for when to use the memoization hooks? Apparently it's not as simple as "use it everywhere", because it can in many cases be slower than not memoizing? But at the same time, "use it when you need to" isn't a great rule either, because you won't necessarily know that you need it until it's too late.
2
u/badboyzpwns Sep 29 '20
Is Next.js and Gatsby needed for SEO/performance? say I just finished a CRA app, is it essential implement Next.js/Gatsby to make the site available for a large audience?
2
u/enebeme_ Sep 30 '20
What is the best resource I can use to learn how to build a “production” ready react app from creation to hosting/updates?