Bashar Boutros
Bashar Boutros

Reputation: 31

Running a child component with a function in parent component

so i have two components a Child "Board.js" that bring an array from backend and build a Board it looks like this:

const Board = (props) => {
const [data, setData] = useState([]);

const newBoard = async (e) => {
    e.preventDefault();
    const data = await fetch('http://localhost:8080/viergewinnt/newboard')
        .then(response => response.json())
        .then(data => {
            // console.log(data);
            return data
        })

    const arr =[];
    data.map(d => arr.push([...d]))
    console.log(arr);
    setData(arr);
}

return (

    <div className='center'>
        <div className='board'>
            { data.map((d) => d.map((v, index) => (<BoardTile  key ={index}/>)))}
        </div>
    </div>
    )

and a parent component "NewGame" which has a button, this button when clicked must build that board in child component. The Parent component looks like this:

const NewGame =  (props) => {

const onClickHandler = () =>{
    return (<Board></Board>)
}

return (
    <div className="App">
        <div>
            <button className='btn' onClick={onClickHandler}>Start new game</button>
        </div>
    </div>
);

PS. the Board was built successfully when all the code was in one Component.

Upvotes: 1

Views: 54

Answers (1)

Mando
Mando

Reputation: 145

import Board from './example.js';
import { useState } from 'react';

const NewGame = (props) => {
  const [boardIsVisible, setBoardIsVisible] = useState(false);

  return (
    <div className="App">
        <div>
        <button 
          className='btn' 
          onClick={() => setBoardIsVisible(true)}>
           Start new game
        </button>

        {boardIsVisible && <Board />}
       </div>
    </div>
   );
}

Upvotes: 1

Related Questions