0

This is my component:

export default function ImageUpload({ onSuccess, children}) {

  let value = '';
  const onUpload = async (element) => {
    element = element.target.files;
    let response;
    // Call endpoint to upload the file 
    value = element[0].name;
    return onSuccess(response.url);   
  };

  return <div>
    <div >
      {children}
      <input type="file" id="upload" onChange={onUpload.bind(this)} />
    </div>
    <span>{value}</span>
  </div>; 
}

I would like to print inside the span the name of the file chosen from the user. I use redux for the state, but this information is not something that belongs to the state. This way does not work, could someone explain me why?

UPDATE Since looks like there is no way to achieve this without state my question is about the best approach: Use Redux also if I don't need this value outside the component or use the internal state of the component but ending to have both Redux and this state?

2
  • 1
    Why do you say that it doesn't belong into the state? The component has to be re-rendered to show the name of the file. You could put at least the name(s) of the file(s) in the state. Commented Feb 20, 2017 at 16:52
  • Because is an information that are useful only inside the component, and never used outside. Commented Feb 21, 2017 at 8:34

1 Answer 1

2

I can think about changing the approach, and transform your component to a class type component, something like that:

export default class ImageUpload extends Component {
  constructor() {
    this.state = {
      value: ''
    }
    this.onUpload = this.onUpload.bind(this)
  }

  onUpload() {
    let value = '';
    const onUpload = async (element) => {
      element = element.target.files;
      let response;
      // Call endpoint to upload the file 
      value = element[0].name;
      this.props.onSuccess(response.url);
      this.setState({ value: value })
    };
  }

  render () {
    return <div>
      <div >
        {children}
        <input type="file" id="upload" onChange={this.onUpload} />
      </div>
      <span>{this.state.value}</span>
    </div>;
  }

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

2 Comments

onUpload bind in render in unnecessary if you bind it in constructor.
So there is no way to achieve this without using the internal state of the component

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.