0

Request.js

export default class Request extends React.Component {
getForm(e) {
  let v = validator(document.getElementById('myinput')); // here is should call function from another class
}
render(){
  return(
      <form onSubmit={this.getForm.bind(this)}>
        <RequestValidator/> // here is I called second class
        <Input id="myinput" value="65"/>
      </form>
    }
  }
}

RequestValidator.js

export default class RequestValidator extends React.Component {
  validator = (e) => { // here is the target function
    console.log(e.value);
  }
}

What I want to do is, pass a variable (#myinput value) from Request compontent class to a function (validator) in another compontent class (RequestValidator).

What I have done so far is above codes, but I got error:

'validator' is not defined no-undef

1
  • 1
    Please indent your code, it looks very messy. Commented Aug 21, 2019 at 19:09

2 Answers 2

2

You can do that using ref. You create one in your parent component:

class Request extends React.Component {
    constructor(props) {
        super(props)
        this.requestValidatorRef = React.createRef();
    }

then you pass it to the child component:

<RequestValidator ref={this.requestValidatorRef} />

at this point you should be able to call your method like this:

getForm(e) {
  this.requestValidatorRef.current.validator(e) // ...
}
Sign up to request clarification or add additional context in comments.

6 Comments

And it return: TypeError: Cannot read property 'current' of undefined
you may need to share your attempt. current can be undefined, because it is set later
Everything is right. but need one change to work. Just remove .current from this.requestValidatorRef.current.validator(e)
No, it is my mistake, it call function, but my code inside the function return nothing, so this problem solved, thanks
By the way document.getElementById('myinput') is not react syntax. react using ref for this.
|
0

If you want to pass parameter to another class in reactjs you should use props. Also variable in requestvalidator class have to use prop name. But in your case RequestValidator and Input components are different. In main component class call like this:

  <UserInput
         titles={this.state.titles}
    />

In UserInput component use this prop like this:

class UserInput extends React.Component {
      componentDidMount() {
        console.log(" titles from main class:", this.props.titles);
      }
}

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.