1
import { Button, Form, FormGroup, Label, Input, FormText } from 'reactstrap';

export default class UserPicForm extends React.Component {

  constructor() {
    super();

    // bindings
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleSubmit(event) {
    event.preventDefault();
    let file = this;
    console.log('this is the file', file);
  }

  render() {
    return (
      <Form onSubmit={this.handleSubmit}>
        <FormGroup>
          <Label for="exampleFile">Upload Image</Label>
          <Input ref={(ref) => this.fileUpload = ref} type="file" name="file" id="exampleFile" />
          <FormText color="muted">
            Please use the field above to upload your profile picture. 
          </FormText>
        </FormGroup>

        <Button type="submit">Upload</Button>
      </Form>
    );
  }
}

I am trying to upload a file and grab it on form submit, I assumed this is done with ref attribute but when I console log my 'this' the refs property is empty. What am I doing wrong?

I also inspected my UserPicForm component using React inspector, the refs section is showing 'null' as well.

0

2 Answers 2

2

Input is a custom element from reactstrap. Taking a look at the source code, it looks like you can get a reference to the input element it renders by using innerRef.

<Input innerRef={(ref) => this.fileUpload = ref} />

When the ref attribute is used on an HTML element, the ref callback receives the underlying DOM element as its argument.

See more information about refs here.

Sign up to request clarification or add additional context in comments.

Comments

0

Shouldn’t need a ref, event.target.elements.file should give the reference to the input.

If you want to use the ref with the way you set it up, your ref is this.fileUpload.

The refs field should have something if you use ref=‘fileUpload’.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.