Functional Components in React

0

I have a Square.js file that contains a function:

function Square(props) {
    <button className="square" onClick={props.onClick}>
        {props.value}
    </button>
}

that would come the functional component that I want to use in another component called Board.js

If I create my Square.js file as a class: class Square extends from React.Component using import Square from './Square.js' works for me, but I want to use a functional component.

how can you reference?

    
asked by Iventura 16.10.2017 в 16:37
source

1 answer

0

Your function needs to return the code you want to display. Your function type component can be used normally from any other component, but if it is in a separate file, the function should be saved and exported. Example of how your file would be Square.js :

import React from 'react';

const Square = function(props) {
  return (
    <button onClick={props.onClick}>
      {props.value}
    </button>
  );
}

export default Square;

The file that will use the function Square must import it with:

import Square from './Square.js';

Example of a Board.js file that uses a function type component Square :

import React from 'react';
import ReactDOM from 'react-dom';
import Square from './Square.js';

class Board extends React.Component {
  render() {
    return(
      <Square onClick = {() => alert('ejemplo')}
              value = "Nombre del botón" / >
    );
  }
}

If you had all the code in a single file, it would be like the following executable example:

function Square(props) {
  return (
    <button onClick={props.onClick}>
      {props.value}
    </button>
  );
}

class Board extends React.Component {
  render() {
    return(
      <Square onClick = {() => alert('ejemplo')}
              value = "Nombre del botón" / >
    );
  }
}

ReactDOM.render( <Board /> , document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="root"></div>
    
answered by 17.10.2017 / 02:50
source