user11461061
user11461061

Reputation:

use state of other class

I am currently working on a school project. I have a map location app. But somehow I need to pass state value coordinates. But I can't share it into the next class... Can someone help me out?

Code:

import React from 'react';
import '../style/card.css';
import '../js/functions/maps';
import Button from './button.js';
import { getLocation } from './functions/getLocation.js';
import './functions/maps';



class Mobile extends React.Component {
  state = {
    coordinates: {}
  };

  getLocationCoordinates = () => {
    getLocation((coordinates) => {
      this.setState({ coordinates });
      console.log(this.state.coordinates);
    });
  };

  functionCoordinatePrint = (index) => {
    return this.state.coordinates[index] ? this.state.coordinates[index] : Math.random() * 50 + 1;
  };

  render() {
    const { lat, lng } = this.state.coordinates;
    return (
      <div id={'location'} className={'card'}>
        <div className={'card-layout'}>
          <div className={'text-card'}>
            <h1>{this.props.header}</h1>
            {this.props.text !== '' && <p className={'max-width-70'}>{this.props.text}</p>}
            <div
              style={{
                color: 'var(--color-text)'
              }}
            >
              <input type="checkbox" id="conditions-read" />
              <a href="../pages/algemene-voorwaarden">Accepteer voorwaarden</a>
            </div>

            <Button function={this.getLocationCoordinates} text={'Allow Location'} />
            <p>{this.props.coordinaten}</p>
          </div>
          <div className={'mobile'}>
            <img src={this.props.device} className={'device'} alt={this.props.alt_image} />
            <div className={'overlay'}>
              <div id={'location-maps'}>
                <iframe
                  title="map"
                  frameBorder="0"
                  scrolling="no"
                  marginHeight="0"
                  marginWidth="0"
                  src={`https://www.mapquest.com/near-${this.functionCoordinatePrint(
                    'latitude'
                  )},${this.functionCoordinatePrint('longitude')}?zoom=3`}
                />
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }
  coordinatesToArray = coordinatesToArray[
    (this.functionCoordinatePrint('latitude'), this.functionCoordinatePrint('longitude'))
  ];
}

class Laptop extends React.Component {
  render() {
    return (
      <div id={'recommendations'} className={'card'}>
        <div className={'card-layout'}>
          <h1>{this.props.header}</h1>

          <div className={'laptop'}>
            <img
              style={{
                width: '150%'
              }}
              src={this.props.device}
              alt={this.props.alt}
            />
            <div className={'overlay-laptop'}>
              <div className={'maps'}>
                <iframe
                  title="mapExample"
                  frameBorder="0"
                  scrolling="no"
                  marginHeight="0"
                  marginWidth="0"
                  src={
                    'https://www.mapquest.com/near-' +
                    (this.props.lat ? this.props.lat : Math.random() * 30 + 1) +
                    ',' +
                    (this.props.long ? this.props.long : Math.random() * 30 + 1) +
                    '?zoom=3'
                  }
                />
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }
}

export { Mobile, Laptop };

I've tried to use props.state.coordinates[0], I also used a global var and have set the values in function GetLocation() and then use it into my Laptop version. But can someone help me?

Thanks in advance.

Upvotes: 0

Views: 83

Answers (3)

Mitch
Mitch

Reputation: 765

What might help you in this case is a Higher Order Component, or HOC for short. You can see a HOC as a parent component where you can store the coordinates. The child components (in your case Mobile and Laptop) can than set and access the data in the HOC allowing the child components to render the coordinates.

Lets clarify this in more detail. First you need to create a HOC component that keeps the coordinates in its state. The HOC should have a setter that needs to be passed to the child components as a property. The value of the coordinates should also be passed to the child components, which we can do using the spread operator.

const withCoordinates = (WrappedComponent) => {
    class WithCoordinates extends Component {
        constructor(props) {
            super(props);
            this.state = {
              coordinates: [],
            };
          }

          setCoordinates = (event) => {
            const { name, value } = e.target;
            this.setState({ [name]: value });    
          }

          render() {
              return (
                    <WrappedComponent
                      setCoordinates={(coordinates) => this.setCoordinates(coordinates)}
                      {...this.state}
                    />
              );
          }
    }

    return WithCoordinates;
}

export default withCoordinates;

Next we need to hook the child components up so it can access the values defined the HOC. Since we passed the coordinates value and the setCoordinates method through the properties we can access them in the child component.

class Laptop extends Component {
    render() {
        const { setCoordinates, coordinates } = this.props;

        return (
            <>
                <input name='coordinates' value={coordinates || ''} onChange={(e) => setCoordinates(e)} />
                <p>The coordinates are {coordinates}</p>
            </>
        );
    }
}

export default WithCoordinates(Laptop);

Notice that the child component is exported along with the WithCoordinates component wrapped around it. This makes it possible for the child component to access the values in the HOC. The name of the input field in the child component corresponds to the state value that is being set in the HOC.

Do not forget to validate the props by using the Proptypes library.

Upvotes: 0

ABGR
ABGR

Reputation: 5205

  1. First separate the the two components, mobile and laptop into separate files. They have their own states to manage and by doing so, you code will be more manageable. then
  2. Import Laptop component into mobile component.
  3. Pass the data into laptop component, for e.g, <Laptop data={this.state.coordinates}/>

  4. Inside your Laptop component get this information with, this.props.data

Upvotes: 0

lsdmt
lsdmt

Reputation: 160

Easiest way would be simply passing the data down through props. If Laptop and Mobile are siblings then you will need to "lift state up" to a common parent component, then you can manage the state in there and pass it down to each of the children using props e.g.

<Mobile myState={myStateVariable} /> <Laptop myState={myStateVariable} />

Upvotes: 0

Related Questions