0

This is my very first app in React. I have created the component and when a user adds text to textArea and clicks on the button, "Download Pdf", I want to pass defaultValue to convertToPdf function.

How do i do that? Basically, I am trying to create a PDF downloader. Any help will be appreciated.

pdfComponent.js

import React, { Component } from "react";
import autosize from "autosize";
import Button from '@material-ui/core/Button';

export class PDFEditorComponent extends Component {

  componentDidMount() {
    this.textarea.focus();
    autosize(this.textarea);
  }
    
  convertToPdf() {
    this.setState(this.textarea);
    console.log("TEXT", this.textarea);
  }
    
  render() {
    const style = {
       maxHeight: "175px",
       minHeight: "450px",
       minWidth: "800px",
       resize: "none",
       padding: "9px",
       boxSizing: "border-box",
       fontSize: "15px"
    };
    return (
       <div>
         PDF Downloader
         <br />
         <br />
         <textarea
              style={style}
              ref={c => (this.textarea = c)}
              placeholder="Paste pdf data"
              rows={1}
              defaultValue=""
         />
         <br />
         <Button
              variant="contained"
              color="primary"
              onClick={() => this.convertToPdf(this.textarea)}
         >
            Download Pdf
         </Button>
       </div>
    );
  }
}
2
  • What is console.log("TEXT", this.textarea); printing? Commented Jul 13, 2020 at 18:48
  • @GrantSingleton its printing html teaxtArea Commented Jul 13, 2020 at 19:02

1 Answer 1

2

Bulletpoints:

  1. Actually create a ref for your textarea (in constructor)
constructor(props) {
    super(props);

    this.textareaRef = React.createRef();
}

then pass it to your textarea element like this

ref={this.textareaRef}
  1. In your convertToPdf() use it like so
this.setState({value: this.textareaRef.current.value})
  1. React state consists of key-value pairs, so you should initialize it in constructor like so
this.state = {
    value: null;
}

and then whenever you want to change it (only from within this component), you call setState(), like I did in p. 2

  1. You are mixing html elements with JS variables: you can't call this.textarea, because it's not a variable (nor constant), so remove all such references to it. In React the only way to access DOM elements is by refs (which you already kind of tried, I corrected you in p. 1).

Enjoy React, it's great :)

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

2 Comments

i dont have constructor so you are saying add constructor and create a ref
thaks for the help

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.