Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Comercial
    • Calculadora

0

43
Vistas
Access a component's children props outside the parent component in react

I have a main page component in react whose render function looks like this

const MainPage = () => {
    return (
         <>
              <Component1 />
              <Component2 />
         </>
    )
}

And Component has some inputs

const Component1 = () => {
    const [val1, setVal1] = React.useState("");
    const [val2, setVal2] = React.useState("");
    return (
         <>
              <input type="text" value={val1} onChange={setVal1} />
              <input type="text" value={val2} onChange={setVal2} />
         </>
    )
}

My question is how to get values val1 and val2 in the MainPage component? Thanks in advance

7 months ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

use Redux or Context API in your React Project. Btw you can call the function to get the children component variables value.

Example React using Class

class Parent extends Component {
  constructor() {
    this.state = {
      value: ''
    };
  }

  //...

  handleChangeValue = e => this.setState({value: e.target.value});

  //...

  render() {
    return (
      <Child
        value={this.state.value}
        onChangeValue={this.handleChangeValue}
      />
    );
  }
}

class Child extends Component {
  //...

  render() {
    return (
      <input
        type="text"
        value={this.props.value}
        onChange={this.props.onChangeValue}
      />
    );
  }
}
7 months ago · Juan Pablo Isaza Denunciar

0

You can't. React is based on Unidirectional Data Flow

So to solve your problem you must define an event that will be called from the children.

const MainPage = () => {
    const [val1, setVal1] = React.useState("");
    const [val2, setVal2] = React.useState("");
    return (
         <>
              <Component1 val1={val1} onChange1={setVal1} val2={val2} onChange2={setVal2} />
              <Component2 />
         </>
    )
}

And Component1

const Component1 = ({val1, onChange1, val2, onChange2}) => {
    return (
         <>
              <input type="text" value={val1} onChange={onChange1} />
              <input type="text" value={val2} onChange={onChange2} />
              />
         </>
    )
}
7 months ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos