r/reactjs • • Apr 30 '20

Needs Help Beginner's Thread / Easy Questions (May 2020)

[deleted] — view deleted post

39 Upvotes

401 comments sorted by

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,

 const [offset, setOffset] = useState(0);
setOffset('hi');

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:

export const useField = () => {
  const [value, setValue] = useState('')

  const onChange = (event) => {
    setValue(event.target.value)
  }

  const reset = () => {
    setValue('')
  }

  return {
    value,
    onChange,
    reset,
  }
}

importing useField into the app to be used as follows:

const handleSubmit = e => {
    e.preventDefault();
    props.addNew({
      content: content.value,
    });
  };
  const handleClear = () => {
    content.reset();
  };
  return (
    <div>
      <form onSubmit={handleSubmit}>
        <div>
          content
          <input {...content} />
        </div>
        <button>create</button>
      </form>
      <button onClick={handleClear}>reset</button>
    </div>
  );
}

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

→ More replies (3)

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?

→ More replies (5)

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:

class StreamCreate extends React.Component {
    renderInput = ({ input, label, meta }) => {
        return (
            <div>
                <input className="createInputs" {...input} autoComplete="off" />
            </div>
        );
    };
    render() {
        return (
            <React.Fragment>
                <div className="createTitle">Create Stream</div>
                <form>
                    <Field name="title" component={this.renderInput} />
                    <Field name="description" component={this.renderInput} />
                    <button>Submit</button>
                </form>
            </React.Fragment>
        );
    }
}
export default reduxForm({
    form: "streamCreate",
})(StreamCreate);

Functional component

const StreamCreate = (props) => {
    const renderInput = ({ input, label, meta }) => {
        return (
            <div>
                <input className="createInputs" {...input} autoComplete="off" />
            </div>
        );
    };

    return (
        <React.Fragment>
            <div className="createTitle">Create Stream</div>
            <form>
                <Field name="title" component={renderInput} />
                <Field name="description" component={renderInput} />
                <button>Submit</button>
            </form>
        </React.Fragment>
    );
};
→ More replies (4)

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:

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.

Edited for clarity.

2

u/badboyzpwns May 12 '20 edited May 12 '20
                        <button className="blackButton">
                            <Link to={`/streams/edit/${stream.id}`}>
                            <h5> Edit </h5>
                             </Link>
                        </button>

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?

→ More replies (10)

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?

→ More replies (2)

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 POST http://localhost:8000/upload/image 404 (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);
      }
    },
}
→ More replies (4)

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

→ More replies (4)

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?

→ More replies (2)

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

import React, { useState } from 'react';
import Button from "./Button";

function App() {

  const [counter, setCounter] = useState(0); 

  const buttonHandler = () => {
    setCounter(counter + 1);
    console.log("counter", counter);
  };

  return (
    <div className="app">
      <div className="deck-container">
        <Button buttonHandler={buttonHandler} counter={0} />
      </div>
    </div>
  );
}

export default App;

Button.js

import React from 'react';

function Button(props) {

  return (
    <div>
      <button onClick={props.buttonHandler}>
          Number of clicks: {props.counter}
      </button>
    </div>
  );
}

export default Button;

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:

const StreamList = (props) => {
    const [streams, setStreams] = useState("");

    useEffect(() => {
        props.fetchStreams();
    }, []);

    return <div>StreamList</div>;
};

vs

class StreamList extends React.Component {
    componentDidMount() {
        this.props.fetchStreams();
    }

    render() {
        return <div>StreamList</div>;
    }
}

I tend not to use setStreams() so it may be redundant. I'm thinking classes are more suitable for this?

→ More replies (2)

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

constructor(){
    super();
    this.state = {
        userId: "" //Set this to "" when deployed
      }
  }

componentDidMount(){
    this.props.user.map((user)=>{
       this.setState({userId: user.User_Id})
    })
} 

render() {    
    return (
        <div>
            <Navbar />
            <CreateRecipeForm userId={this.state.userId}/>  //Called before state gets set
        </div>
    )
}
→ More replies (2)

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,

<button onClick= {() => {callMe("ok")}/> 

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

<button onClick={callMe.bind(this, "ok")}/>

a better alternative?

→ More replies (10)

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?

→ More replies (5)

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.

→ More replies (8)

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>
);

→ More replies (5)

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)

    const [offset, setOffset] = useState(0); //get scroll position
    useEffect(() => {
        window.onscroll = () => {
            setOffset(window.pageYOffset); //re-renders onScroll
        };
    }, []);

//Repeated code
    const renderNav = () => {
        if (offset < 100) {
        
            return(
            <nav className="offsetInitial">
  
                <GoogleAuth />
                {renderCreate()}
              ...other HTML elements
            </nav>
 
            )
        } else {
            return(
                <nav className="offsetScroll"> //different class
                    <GoogleAuth />
                    {renderCreate()}
                ...other HTML elements
                </nav>
                )
        }
    };

    return (
      return <React.Fragment>{renderNav()}</React.Fragment>;
    );
→ More replies (8)

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?