Home > database >  Min and Max of a grid with props in React
Min and Max of a grid with props in React

Time:11-07

I wrote this code for an adjustable grid screen, it works perfectly fine but the only problem I have is that, I want the min and mix of it be 16 x 100. so when a button is clicked, a prompt window pops up and asks for the Grid size, you can put only between 16-100, but when I put 120, it still works, however I don't want it to be like this, how can I change it so it works as stated?

const sketchpad = (props) => {
const sketchSize = Math.min(props.portSize.width, props.portSize.height - 50);

const cellSize = Math.round(sketchSize / props.size);

const divSize = Math.max(sketchSize, cellSize * props.size);

const grid = props.pixelData.map((pixel, idx) => (
 <Cell
  cellSize={cellSize}
  sketchSize={sketchSize}
  bgColour={pixel}
  keys={idx}
  key={idx}
  onMouseDown={props.mouseDown}
  setColor={props.setColor}
/>
));

return (
<div className={`d-flex justify-content-center ${classes.SketchContainer}`}>
  <div
    className={`my-3 ${classes.Sketchpad}`}
    style={{ height: `${divSize}px`, width: `${divSize}px` }}
    onMouseUp={props.mouseUp}
  >
    {grid}
  </div>
</div>
  );
  };

and my propmt

const gridSize = prompt("Please enter grid size");
  if (gridSize < 100 && gridSize > 16) {
    setGridSize(gridSize);
    newPixelData = initPixelData(gridSize, INIT_BG_COLOUR);
  } else {
    alert("choose between 16-100")
    const gridSize = prompt("Please enter your number");
    setGridSize(gridSize);
    newPixelData = initPixelData(gridSize, INIT_BG_COLOUR);
  }

CodePudding user response:

Here is an example using while which will run the loop until a value that meets all conditions is entered. (I added a an isNaN check as you'll also want to confirm that the returned value is even a number.)

let gridSize = prompt('Please enter grid size');

// if gridSize isn't a number OR is greater than 100 OR is less than 16, run the loop again
while (isNaN(gridSize) || gridSize > 100 || gridSize < 16) {
  alert('choose between 16-100');
  gridSize = prompt('Please enter your number');
}

console.log(gridSize);

// setGridSize(gridSize);
//  newPixelData = initPixelData(gridSize, INIT_BG_COLOUR);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related