0

I'm importing a class from another script in my main React App, and would like to access a variable within that class from the main App. Basically the user types something into a textbox, then clicks a button to add that value to a variable. In the main App I import that class, then have another button to print those values (selectedvalues). I'm not entirely sure how to do it, but this is my code so far:

Class I am importing:

import React, { Component } from 'react';

class MyModule extends Component {

    constructor() {
        super();
        this.state = {
            selectedValues: '',
        }
     }

    addValue() {
        this.selectedValues += document.getElementById('textBox1').value + ', '
        return this.selectedValues  
    }

    render() {
        return(
            <div>
                <input type='text' id='textBox1' />
                <button onClick={() => this.addValue()}>Add Value</button>
            </div>
        )
    }
  }

export default MyModule

And where I would like to actually access that value

import React, { Component } from 'react';
import MyModule from './myModule.js'

class App extends Component {

    constructor() {
        super();
        this.state = {

        }
     }

    printValues() {
         console.log(document.getElementById('themodule').selectedvalues)
     }

    render() {
        return(
            <MyModule id='themodule' />
            <button onClick={() => printValues()}>Print values</button>
        )
    }
  }

export default App

Is there a way I can do this?

Thanks!

3
  • 1
    You can use React Context (reactjs.org/docs/context.html) to share state between components, or let the parent component (<App/> in this case) handle the state and pass it on to the child component (<MyModule/>). Commented May 22, 2019 at 12:53
  • I used to store that kind of variables at topLevel, and then, I send as a property: <MyModule id=... selectedValues={this.state.selectedValues} addValue={this.addValue} Commented May 22, 2019 at 12:54
  • So define the selected values variable in the this.state={selectedValues: ''}, on the App.js side, then how would I get that into the myModule.js file? Commented May 22, 2019 at 13:02

3 Answers 3

2

Edit JS-fiddle here https://jsfiddle.net/xzehg1by/9/

You can create Refs and access state and methods from it. Something like this.

constructor() {
   this.myRef = React.createRef();
}

render() { ... <MyModule id='themodule' ref={this.myRef} /> }

printValues() {
   console.log(this.myRef)
}

more info here https://reactjs.org/docs/refs-and-the-dom.html

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

2 Comments

Thanks. Can I access the state values from MyModule like this? When console.log this.myRef, it just returns current: null. I also get a warning saying :components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()? Not sure how that impacts the functionality
@Djaenike Yes. You can use refs to access the state and all methods private to MyModule using current. I have created a fiddle for you please check jsfiddle.net/xzehg1by/9
1

Basically, your state (selectedValues) has to go one level up in the React tree. You have to declare it as App's state, and then pass it down to MyModule via props.

Btw in addValue(), you're not changing any state. And this.selectedValues will be undefined. It's this.state.selectedValues, and this.props.selectedValues once you correct your code.

1 Comment

well noted... the selectedValues update has a error because it doesn't use the setState
0

I think you should first read all react concepts and then start working on it. Anyhow i am modifying your code in one way to get your desired functionality but remember this is not best practice you have to use Redux for this kind of features

import React, { Component } from 'react';

class MyModule extends Component {

    constructor() {
        super(props);
        this.state = {
            inputValue : ''
        };
        this.handleInput = this.handleInput.bind(this);
        this.addValue = this.addValue.bind(this)
    }
    handleInput(e){
        this.setState({
            inputValue : e.target.value
        })
    }
    addValue() {
        this.props.addValue(this.state.inputValue);
    }

    render() {
        return(
            <div>
                <input type='text' id='textBox1' onChange={handleInput} />
                <button onClick={this.addValue}>Add Value</button>
            </div>
        )
    }
}

export default MyModule

and your main component should be

import React, { Component } from 'react';
import MyModule from './myModule.js'

class App extends Component {

    constructor() {
        super(props);
        this.state = {
            selectedValues : ''
        };
        this.printValues = this.printValues.bind(this);
        this.addValues = this.addValues.bind(this);
    }

    printValues() {
        console.log(this.state.selectedValues);
    }

    addValues(val){
        this.setState({
            selectedValues : this.state.selectedValues + " , "+val
        })
    }
    render() {
        return(
            <React.Fragment>
            <MyModule addValue={this.addValues}/>
            <button onClick={this.printValues} >Print values</button>
            </React.Fragment>
        )
    }
}

export default App

This should do your work

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.