I'm using Calendar andt and facing the problem, when I'm in the current month, if I choose to change the month, Calendar automatically updates the date of the old month to the date of the new month.
Example: I am in 2022-07-20 then I select August then Calendar will update itself to 2022-08-20
This also fires onChange and onSelect events, I just want the onChange and onSelect events to be fired when the user clicks on the date in the calendar, how can I prevent it from updating itself?
Code here :
const customHeaderCalendar = ({ value, type, onChange, onTypeChange }) => {
let yearNow = parseInt(moment().format('YYYY'));
const year = value.year();
const month = value.month();
const options = [];
for (let i = year - 10; i < year + 10; i += 1) {
if (i >= yearNow){
options.push(
<Select.Option key={i} value={i} className="year-item">
{i}
</Select.Option>,
);
}
}
const start = year == yearNow ? parseInt(moment().format('M')) - 1 : 0;
const end = 12;
const monthOptions = [];
const current = value.clone();
const localeData = value.localeData();
const months = [];
for (let i = 0; i < 12; i++) {
current.month(i);
months.push(localeData.monthsShort(current));
}
for (let i = start; i < end; i++) {
monthOptions.push(
<Select.Option key={i} value={i} className="month-item">
{months[i]}
</Select.Option>,
);
}
return (
<div
style={{
padding: 8,
display: 'flex',
justifyContent: 'space-between'
}}
>
<span style={{fontSize: '16px'}}>Select date</span>
<Row gutter={8}>
<Col>
<Select
size={'small'}
dropdownMatchSelectWidth={false}
className="my-year-select"
value={year}
onChange={(newYear) => {
const now = value.clone().year(newYear);
onChange(now);
}}
>
{options}
</Select>
</Col>
<Col>
<Select
size="small"
dropdownMatchSelectWidth={false}
value={month}
onChange={(newMonth) => {
const now = value.clone().month(newMonth);
onChange(now);
}}
>
{monthOptions}
</Select>
</Col>
</Row>
</div>
);
}
<Calendar
headerRender={customHeaderCalendar}
defaultValue={valueDefaultDatePicker}
disabledDate={disabledDate}
onSelect={onChangeDepartureDay}
fullscreen={false}
onChange={() => console.log('onchange')}
/>
Thanks
I think you sound make a condition to avoid this in onSelected. It keeps choosing unexpected date in UI, but you can do the logic with the right selected date.
onSelect={(date: moment.Moment) => {
if(
date.isSameOrAfter(startDate, "day") &&
date.isSameOrBefore(endDate, "day")
)
//do something
}}
I am attempting to in React JS to get the sum of a group inputs, and put the sum of their total values in a div tag.
I am trying to run this event whenever a user types in any of the inputs
The problem is I am sure React has a proper way to do this!
This is my feeble attempt (please go easy - I am new to coding :)
HTML
<input type="number" id="comp1" name="comp1" onChange={this.handleTotal} />
<input type="number" id="comp2" name="comp2" onChange={this.handleTotal} />
<input type="number" id="comp3" name="comp3" onChange={this.handleTotal} />
<input type="number" id="comp4" name="comp4" onChange={this.handleTotal} />
<input type="number" id="comp5" name="comp5" onChange={this.handleTotal} />
<input type="number" id="comp6" name="comp6" onChange={this.handleTotal} />
<div id=total></div>
JS
handleTotal = e => {
// Grab all inputs that start with ID 'comp'
let inputs = document.querySelectorAll('[id^="comp"]');
// Trying to loop through the values and get the sum of all inputs
for (var i = 0; i < inputs.length; i++) {
let totalVal = inputs[i].value
console.log(totalVal);
}
//Trying to grab total values of all inputs and put in element
document.getElementById('total').innerHTML = totalVal;
}
At the moment you are not utilizing any of the React's data binding.
Best to use React's state to hold the values of the total and all the comp inputs.
I've also used the .reduce method in order to calculate the total for each of the input fields' values. But you can achieve the same thing with a for loop.
JSFiddle: Alternative "calculateTotal" function with for loop
More information on Input handling in React
class App extends React.Component {
constructor() {
super();
this.state = {
total: 0,
numbers: {
comp1: 1,
comp2: 0,
comp3: 4,
comp4: 0,
comp5: 0,
comp6: 0
}
};
}
componentDidMount() {
// Calculates the total after component is mounted
this.setState({ total: this.calculateTotal(this.state.numbers) });
}
calculateTotal = (numbers) => {
return Object.entries(numbers).reduce((finalValue, [key, value]) => {
if (value === "") {
// if entered value is empty string "", omits it
return finalValue;
}
return finalValue + value;
}, 0);
}
handleTotal = (e) => {
const { value, name } = e.target; // gets the name and value from input field
const parsedValue = value === "" ? "" : parseFloat(value); // parses the value as a number or if empty treats it as empty string ""
this.setState((prevState) => {
// creates new immutable numbers object, using previous number values and the currently changed input value
const updatedNumbers = {
...prevState.numbers,
[name]: parsedValue
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#Computed_property_names
};
// calculates the new total from updated numbers:
const newTotal = this.calculateTotal(updatedNumbers);
return {
numbers: updatedNumbers,
total: newTotal
}
})
}
render() {
return (
<div>
<input type="number" name="comp1" onChange={this.handleTotal} value={this.state.numbers.comp1} />
<input type="number" name="comp2" onChange={this.handleTotal} value={this.state.numbers.comp2}/>
<input type="number" name="comp3" onChange={this.handleTotal} value={this.state.numbers.comp3}/>
<input type="number" name="comp4" onChange={this.handleTotal} value={this.state.numbers.comp4}/>
<input type="number" name="comp5" onChange={this.handleTotal} value={this.state.numbers.comp5}/>
<input type="number" name="comp6" onChange={this.handleTotal} value={this.state.numbers.comp6}/>
<div id="total">{this.state.total}</div>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
You just re-assign variable in every iteration of a loop. Change to smth like this:
handleTotal = e => {
// Grab all inputs that start with ID 'comp'
let inputs = document.querySelectorAll('[id^="comp"]');
// Trying to loop through the values and get the sum of all inputs
let totalVal=0
for (var i = 0; i < inputs.length; i++) {
totalVal += inputs[i].value
console.log(totalVal);
}
//Trying to grab total values of all inputs and put in element
document.getElementById('total').innerHTML = totalVal;
}
+= operator just adds value of next element to total variable. it is equal to totalVal = totalVal + inputs[i].value
const handleFormSubmit = (e) => {
e.preventDefault();
const formData = new FormData(e.target);
let total = 0;
for (let [key, value] of formData.entries()) {
total += value * 1;
}
document.querySelector('#total').textContent = total;
};
document.addEventListener('DOMContentLoaded', () => {
const form = document.querySelector('form');
form.addEventListener('submit', handleFormSubmit, false);
});
<form>
<input type="number" id="comp1" name="comp1" />
<input type="number" id="comp2" name="comp2" />
<input type="number" id="comp3" name="comp3" />
<input type="number" id="comp4" name="comp4" />
<input type="number" id="comp5" name="comp5" />
<input type="number" id="comp6" name="comp6" />
<button type="submit">submit</button>
</form>
<span>total</span>
<div id=total></div>
I am trying to create four inputs and display all of them after clicking the button. However it returns null. What's wrong with my code?
function addname() {
for (count = 0; count < 5; count++) {
var x = " ";
var inputID = "clientname" + (count + 1);
x = document.getElementById(inputID).value
}
var f = "";
for (var count = 0; count < 5; count++) {
f += x[count];
}
document.write(f)
}
<input type="text" id="clientname1" />
<input type="text" id="clientname2" />
<input type="text" id="clientname3" />
<input type="text" id="clientname4" />
<button onclick="addname()"></button>
Immediate fix: There are 4 inputs, not 5, and stop x from being abused:
function addname() {
var names = [];
for (count = 0; count < 4; count++) {
var inputId = " clientname" + (count + 1);
var name = document.getElementById( inputId ).value;
names.push( name );
}
var f = "";
for (var count = 0; count < 5; count++) {
f += names[count];
}
document.getElementById( 'output' ).textContent = f; // Never use `document.write`!
}
<input type="text" id="clientname1" />
<input type="text" id="clientname2" />
<input type="text" id="clientname3" />
<input type="text" id="clientname4" />
<button onclick="addname()">Concatenate names</button>
<span id="output"></span>
Revision 2: Simplified: Using querySelectorAll with a substring attribute match, and join to concatenate strings:
function concatenateNames() {
const inputs = document.querySelectorAll( 'input[type=text][id^="clientname"]' );
const names = []; // `const` means the variable cannot be reassigned, not that it's immutable.
for( let i = 0; i < inputs.length; i++ )
{
names.push( inputs[i].value );
}
const allNames = names.join( " " );
document.getElementById( 'output' ).textContent = allNames;
}
Revision 3: Simplified further, using Array.from so we can use map with NodeListOf<T>, and adding filter to exclude empty values:
function concatenateNames() {
const inputs = Array.from( document.querySelectorAll( 'input[type=text][id^="clientname"]' ) );
const names = inputs.map( inputEl => inputEl.value ).filter( n => n.length > 0 );
const allNames = names.join( " " );
document.getElementById( 'output' ).textContent = allNames;
}
Revision 4: Simplified further, inlining intermediate variables only used once:
function concatenateNames() {
document.getElementById( 'output' ).textContent =
Array.from(
document.querySelectorAll( 'input[type=text][id^="clientname"]' )
)
.map( inputEl => inputEl.value )
.filter( n => n.length > 0 )
.join( " " );
}
Revision 5: Using nextElementSibling and an inline onclick handler in a single line and shortening identifiers:
<input type="text" id="clientname1" />
<input type="text" id="clientname2" />
<input type="text" id="clientname3" />
<input type="text" id="clientname4" />
<button onclick="this.nextElementSibling.textContent = Array.from( document.querySelectorAll('input[type=text][id^=clientname]') ).map(i => i.value).filter(n => n.length > 0).join(' ')">Concatenate names</button>
<span id="output"></span>
Never do this in production code.
JSFiddle demo: https://jsfiddle.net/3md65awo/
Javascript stops running at the error upon count = 4 trying to get element by id "clientname5"
Either add another text input or change loop to "count = 0; count < 4; count++"
Try this code. I used jquery for this.
function addname() {
for (var count = 1; count < 5; count++) {
var x;
x = $("#clientname" +count).val()
console.log(x)
$("#test").append(x)
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="inp" id="clientname1" />
<input type="text" name="inp" id="clientname2" />
<input type="text" name="inp" id="clientname3" />
<input type="text" name="inp" id="clientname4" />
<label id = "test"></label>
<input type="button" onclick="addname()" value="click" />
I have a little issue with React. I can't create a nested component with a for loop. What I want to do is create 9 cells of a table and then create 3 rows with 3 cells for every row and after that mount the 3 rows together and create a board 9x9.
Let say that I want to get something like this, but using a loop
class Board extends React.Component {
renderSquare(i) {
return <Square value={this.props.squares[i]} onClick={() => this.props.onClick(i)} />;
}
render(){
return(
<div>
<div className="board-row">
{this.renderSquare(0)}
{this.renderSquare(1)}
{this.renderSquare(2)}
</div>
<div className="board-row">
{this.renderSquare(3)}
{this.renderSquare(4)}
{this.renderSquare(5)}
</div>
<div className="board-row">
{this.renderSquare(6)}
{this.renderSquare(7)}
{this.renderSquare(8)}
</div>
</div>
);
}
}
I searched others question for hours and I think my code is almost correct but it does not render what I want. I only get a white page.
here is my code:
class Board extends React.Component {
renderSquare(i) {
return <Square value={this.props.squares[i]} onClick={() => this.props.onClick(i)} />;
}
createCells(i){
if(i%3){return;}
var index = this.fillN(Array(i)); //index=[0,1,2,3,4,5,6,7,8]
var cells = [];
index.forEach(function(i){
cells.push(() => {
return(
<div>
{this.renderSquare(i)}
</div>
);
});
});
return cells;
}
createRows(cells){
var index = this.fillMod3(Array(3)); //index=[0,3,6]
var rows = []
index.forEach(function(i){
rows.push(() => {
return(
<div>
{cells[i]}
{cells[i+1]}
{cells[i+2]}
</div>
);
});
});
return rows;
}
render(){
var cells = this.createCells(9);
var rows = this.createRows(cells);
var board = [];
var index = this.fillN(Array(1));
index.forEach(function(row){
board.push(() => {
return(
<div>{row}</div>
);
});
})
return(
<div>
{board[0]}
</div>
);
}
I always get on the screen something like this:
<Board>
<div> /*empty*/ </div>
</Board>
I want to clarify that I am sure that the rest of the code with which that component (Board) interacts has no issues.
I am new in react and if someoane can help me i will apreciate very much.
Sorry for my poor English
EDIT1:
following marklew examples i should be able to do something like this
render(){
var index1 = this.fillN(Array(3)); //index1=[0,1,2]
var index2 = this.fillN(Array(3)); //index2=[0,1,2]
return(
<div>
{index1.map((e1,i1) => {
return(
<div key={i1} className="board-row">
{index2.map((e2, i2) => {
return(
<p key={i2+10}>
{this.renderSquare(i2)}
</p>
)
})}
</div>
)
})}
</div>
);
}
but it doesn't do what I want. I obtain just a column with 9 cells and the cells are the same objects. I dont understand why. (I understand that are the same objects because i assign a handle function onClick when I create them like that:
<Board
onClick={(i) => this.handleClick(i)} //handleClick just draws a X in the cell
/>
and I get the X drown in 3 cells simultaneously
EDIT2:
I reached a solution:
render(){
var index1 = this.fillMod3(Array(3));
return(
<div>
{index1.map((e,i) => {
return(
<div key={i} className="board-row">
{this.renderSquare(e)}
{this.renderSquare(e+1)}
{this.renderSquare(e+2)}
</div>
)
})}
</div>
);
}
}
but is not what I want. I want another loop even for the intern renderSquare(i) function.
To render a list of elements inside JSX, you can do something like that:
render() {
return <div>
{
[1,2,3].map ( (n) => {
return this.renderSquare(n)
})
}
</div>;
}
Just wrap your array of components into {} in your JSX.
To clarify a bit, this is the same logic of:
return <div>
{
[
<h1 key="1">Hello 1</h1>,
<h1 key="2">Hello 2</h1>,
<h1 key="3">Hello 3</h1>
]
}
</div>;
Note that everytime you render an array of components, you must provide a key prop, as pointed here.
Also, if you want simply print row value in your render function, you should replace:
index.forEach(function(row){
board.push(() => {
return(
<div>{row}</div>
);
});
})
with:
index.forEach( (row, index) => {
board.push(<div key={index}>{row}</div>)
})
or, yet, replacing forEach and push with map:
board = index.map( (row, index) => <div key={index}>{row}</div> )
EDIT I created a fiddle with a 9x9 board using your code as a base: https://jsfiddle.net/mrlew/cLbyyL27/ (you can click on the cell to select it)
I see you too are doing the JS React tutorial! Here's what I did, but I'm working on this because there has to be a good way to give each of these individual keys.
I ran into the same issue you were running into where the X's were drawn into 3 squares, and the reason that happens is because when you were rendering squares, some of the "i's" were duplicated. So there were multiple Squares with the "i" of 2 for example (at least that was the case in my issue).
So each Square has an index right? [0,1,2,3,4,5,6,7,8].
First we need to find how these are related in a way that we can render them into rows! So, in your example you have index1 and index2, which I assume will refer to the x and y coordinates of the Square in the Board. Re-writing the array above we come to: [{0,0}, {1,0}, {2,0}, {0,1}, {1,1}, {2,1}, {0,2}, {1,2}, {2,2}] using {x,y} format. How can we use these values (which we would get from your index1 and index2 in order to get the original array of values that we started with [0,1,2,3,4,5,6,7,8]?
What I did was 3 * x + y (or in a loop, 3 * i + j). This way each square has a unique "i" value associated with it.
After I set up my loops I used this SO post to correctly return the elements I created from a separate function (in a poor attempt to keep my code cleaner).
This is what I ended up with, but I need to make sure to set the keys correctly which is actually how I stumbled onto this post:
createSquares() {
let rows = [];
for(var i = 0; i < 3; i++){
let squares = [];
for(var j = 0; j < 3; j++){
squares.push(this.renderSquare(3*i+j));
}
rows.push(<div className="board-row">{squares}</div>);
}
return rows;
}
Then my render function in Board looks like this:
render() {
return (
<div>
{this.createSquares()}
</div>
);
}
Here is the best I could think of after reading answers here and in Loop inside React JSX
:
render() {
return (
<div>
{
[...Array(3)].map((_, i) => (
<div key={i} className="board-row">
{
[...Array(3)].map((_, j) => this.renderSquare(3 * i + j))
}
</div>
))
}
</div>
);
}
P.S. I'm also doing the challenges in the new React Tutorial. =p
Live demo on codepen
Nested loops in render() function
(explanation in comments:)
class Board extends React.Component {
renderSquare(i) {
return (
<Square
value={this.props.squares[i]}
key={i}
onClick={() => this.props.onClick(i)}
/>
);
}
render() {
var self = this;
return (
<div>
// you can use: [...Array(3)] instead of [1,2,3]
{[1, 2, 3].map(function(row, rowIdx) { // create rows
return (
<div className="board-row" key={rowIdx}>
{
// you can use: [...Array(3)] instead of [1,2,3]
[1, 2, 3].map((col, colIdx) => { // create columns
return self.renderSquare((3 * rowIdx) + colIdx); // calculate square index
})
}
</div>
);
})}
</div>
);
}
}
I will assume you are looking at the React Tutorial example.. As the instructions explicitly point out, the idea is to make two loops, not just the one.
The first loop in this example creates the 3 rows. The second nested loop creates the 3 necessary columns, returning a Square for each position through the renderSquare function. You may notice that I use the indexes of both loops to correctly assign the corresponding index to the square.
return (
<div>
{[0,1,2].map(i => {
return (
<div className="board-row">
{[0,1,2].map(j => {
return this.renderSquare(3*i + j)
})}
</div>
);
})}
</div>
);
Here's my solution. It may help.
renderSquare(i) {
return (
<Square
key={i}
value={this.props.squares[i]}
onClick={() => this.props.onClick(i)}
/>
);
}
render() {
let rows = [];
for (let i = 0; i <= 2; i++) {
let children = []
for (let j = i * 3; j <= i * 3 + 2; j++) {
children.push(this.renderSquare(j))
}
rows.push(
<div key={i} className="board-row">
{children}
</div>
)
}
return (
<div>
{rows}
</div>
);
}
This snippet uses map in a way similar to how we define a nested loop.
const buildBoard = [0, 1, 2].map((row) => {
return (
<div className='board-row' key={row}>
{[0, 1, 2].map((col) => {
return this.renderSquare(row * 3 + col);
})}
</div>
);
});
return <div id='Board Container'>{buildBoard}</div>;
You are pushing functions to the board array. If you want render them, you have to call those functions like
{board[0]()}
I prepared an example that covers your problem: http://jsbin.com/hofohiy/edit?js,output
I'm working on the React tutorial also. Thanks for your responses. I got to this solution:
render() {
const rows = [];
for(let i = 0; i<9; i=i+3) {
const oneRow = [];
for(let j = i; j < i+3; j++) {
oneRow.push(this.renderSquare(j, j))
}
rows.push(<div className="board-row" key={i + 'someId'}>{oneRow}</div>)
}
return (
<div>
{rows}
</div>
);
}
Where I changed renderSquare to set a key for the Square component, as the second argument.
renderSquare(i, key) {
return (
<Square
value={this.props.squares[i]}
onClick={() => this.props.onClick(i)}
key={key}
/>
);
}
This should resolve the problem your facing.
This adds another loop even for the intern renderSquare(i) function.
It does what you want i.e. display 3 columns with 3 cells for the tic tac toe game.
render() {
let count = 0;
const index = [1, 2, 3];
return (
<div>
{index.map((v, i) => {
return (
<div key={i} className="board-row">
{index.map((v2, i2) => {
return this.renderSquare(count++);
})}
</div>
);
})}
</div>
);
}
The first solution:
import React from 'react';
import Square from './Square';
export default
class Board extends React.Component {
render() {
const board2 = [];
for (let i = 0; i < 3; i++) {
const s = [];
for (let k = 0; k < 3; k++) {
s[k] = <Square
key ={3*i+k}
value ={this.props.squares[3*i+k]}
onClick ={()=>this.props.onClick(3*i+k)}
/>;
}
board2[i] = <div className="board-row" key={i}>{s}</div>;
}
///////////////////////////////////////
return (
<div>{board2}</div>
);
}
}
The second solution:
import React from 'react';
import Square from './Square';
export default
class Board extends React.Component {
render() {
let board =Array(3).fill(null);
let square =Array(3).fill(null);
const x = board.map((b,bIndex)=>{
return<div className="board-row" key={bIndex}>
{
square.map((s, sIndex)=>{
return <Square
key ={3*bIndex+sIndex}
value ={this.props.squares[3*bIndex+sIndex]}
onClick ={()=>this.props.onClick(3*bIndex+sIndex)}
/>;
})
}
</div>;
});
///////////////////////////////////////
return (
<div>{x}</div>
);
}
}
Square:
import React from 'react';
export default
function Square(props) {
console.log('square render')
return (
<button className="square" onClick={props.onClick}>
{props.value}
</button>
);
}
class Board extends React.Component {
renderSquare(i) {
return (<Square key={i} value={this.props.squares[i]} onClick={() => this.props.onClick(i)} />);
}
render() {
let board = [];
for(let x = 0; x<3; x++){
let lis =[];
for(let y = 0; y<3; y++){
lis.push(this.renderSquare(3*x + y));
}
board.push(<div key={x}>{lis}</div>)
}
return (
<div>
{board}
</div>
);
}
}
My solution is:
class Board extends React.Component {
//range is a Sequence generator function
//Array.from(arrayLike[, mapFn [, thisArg]]).
//arrayLike - An array-like or iterable object to convert to an array
//mapFn - Map function to call on every element of the array
//thisArg - Value to use as this when executing mapFn
//range(0, 4, 1); => [0, 1, 2, 3, 4]
range = (start, stop, step) => Array.from(
{ length: (stop - start)/step +1 },
(_, i) => start + (i * step)
);
renderSquare(i) {
return <Square
key={i}
value={this.props.squares[i]}
onClickChange={() => this.props.onClickChange(i)}
/>;
}
render() {
let row = 3;
let col = 3;
return (
<div>
{
//This generates an Array of [0, 3, 6] if row = 3 and col = 3
// n is the element and i is the index of the element, i starts at 0
this.range(0, row * col - 1, col).map( (n, i) => {
return (
<div key={i} className="board-row">
{
this.range(n, (i + 1) * col - 1, 1).map( (n, i) => {
return this.renderSquare(n)
})
}
</div>
)
})
}
</div>
);
}
Changed the code of the Board from the tutorial to reflect as
class Board extends React.Component {
constructor(props) {
super(props);
this.rows = Array(3).fill(null);
}
renderSquare(i) {
return (<Square
key={i}
value={this.props.squares[i]}
onClick={() => this.props.onClick(i)}
/>);
}
renderRow(row) {
return (
<div key={row} className="board-row">
{this.rows.map((x, col) => this.renderSquare(3*row+col))}
</div>
);
}
render() {
return (
<div>
{this.rows.map((x, rowIndex) => this.renderRow(rowIndex))}
</div>
);
}
}
The answers above that provide an array, defeat the purpose of a loop; this isn't pretty, but then again, neither is React with JSX:
class Board extends React.Component {
render() {
let board=[];
for(let row=0;row<9;row+=3) {
let cols=[];
for(let col=0;col<3;col++) {
let i=col+row;
cols.push(<Square value={this.props.squares[i]} onClick={() => this.props.onClick(i)}/>)
}
board.push(
<div className="board-row">
{cols}
</div>
);
}
return (
<div>
{board}
</div>
);
}
}
hmm, i think it's way simpler nowadays, cuz i just did
export default function Board(props){
return(
<div id = "board">
{createBoard(3, 3)}
</div>
)
}
function Square(props){
return(
<div className = "boardSquare" style = {{
gridColumn: props.x,
gridRow: props.y}}>
</div>
)
}
function createBoard(x, y){
// x and y being the max "cells" my board will have
let grid = [];
for(let i = 0; i < x; i++){
for(let u = 0; u < y; u++){
grid.push(<Square x = {i + 1} y = {u + 1} key = {`x${i+1}y${u+1}`}/>);
}
}
return grid;
}
and it did exactly what i wanted it to, so yeah, just returning an array solved my problem, i hope my answer is useful to someone.
Just for giggles here's a recent working example as a function component
import React from "react";
import Square from "./Square";
import "./Board.css";
export default function Board(props) {
function renderSquare(i) {
return (
<Square
key={i}
value={props.squares[i]}
onClick={() => props.onClick(i)}
/>
);
}
return (
<div className="board-wrapper">
{
[...Array(3).keys()].map( row => (
<div key={row} className="board-row">
{
[...Array(3).keys()].map( col => renderSquare((row * 3) + col))
}
</div>
)
)
}
</div>
)
}