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

44
Vistas
On clicking component redirect to custom component

I am practising react. I have some boxes displayed on UI and clicking on a particular box should open a page corresponding to that box. For e.g If a click on Box 1 it should open a page(another component) which displays text "Box 1 Clicked". Currently i am just able to log box id on console but don't know how to redirect. Below is my code.

App.js

import React from 'react'
import boxes from './data'
import Box from './Box'
import './style.css'

export default function App(props) {

  const [squares, setSquare] = React.useState(boxes)

  function toggle(id){
    console.log(id)
  }

  const squareElements = squares.map(sqaure => (
        <Box 
            key={sqaure.id} 
            id={sqaure.id}
            on={sqaure.on} 
            toggle={toggle}
        />
  ))

  return (
    <main>
        {squareElements}
    </main>
  )
}

Box.js

import React from 'react'

export default function Box(props) {

    const styles = {
        backgroundColor : props.on ? "black" : "white"
    }


    return (
        <div 
            style={styles} 
            className='box'
            onClick={() => props.toggle(props.id)}
        ></div>
    )
}

This is the component which i want to display on clicking a box.

BoxInfo.js

import React from 'react'

export default function BoxInfo(props) {
    return (
        <h2>Clicked {props.id}</h2>
    )
}

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

0

You can render it on the same page depending on the selected box.

App.js

import React from 'react'
import boxes from './data'
import Box from './Box'
import './style.css'

export default function App(props) {

  const [squares, setSquare] = React.useState(boxes)
  const [activeBox, setActiveBox] = React.useState()

  function toggle(id){
    setActiveBox({id})
  }

  const squareElements = squares.map(sqaure => (
        <Box 
            key={sqaure.id} 
            id={sqaure.id}
            on={sqaure.on} 
            toggle={toggle}
        />
  ))

  if(activeBox){
    return <BoxInfo {...activeBox} /> 
  }

  return (
    <main>
        {squareElements}
    </main>
  )
}
7 months ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos