Skip to content

Interesting Code Bits

Andrew edited this page Oct 16, 2021 · 2 revisions

For conditionally rendering an image

Our canvases (boards) that are displayed on the users homescreen may or may not have inks (images/pins) on them. If they are "blank"(don't have inks), I still wanted them to have some nice image on the tile. I made two conditional statements to render image elements. The first would see if the canvas in question had any inks, and if so it would place an element that used the first ink as the image to display. The second worked in the opposite way. If the canvas in question had no inks, then an image element is rendered that uses a default image. I thought this solution came out really well since its very short, requires little calculation, and is very readable.

{ canvas.inks[0] &&
   <img src={canvas.inks[0].image} />}
{ !canvas.inks[0] &&
   <img src={defaultCanvasCover} />}

For handling errors on a form:

We used to do set a state that would keep track of if there were errors. If that array had length then the submit button was disabled:

const [name, setName] = useState('');
const [errors, setErrors] = useState([]);

useEffect(() => {
   let newErrors = [];
   if (name.length < 2 ) newErrors.push("Name must be at least 3 characters")
   setErrors(newErrors)
}, [name])
...

<button disabled={errors.length} >Submit </button>

I've never liked how this caused the errors to all show up on the first render before the user had added any input. So I added a separate state to instead show/hide the block of errors. The first time the user hits submit, the error messages are revealed (if they exist). The submit button is never disabled, but the handling of the submit will have no effect if errors has length. The only downside to this is that the submit button is not disabled/greyed out if errors are present. But I think its a good tradeoff since the user is not told 'you filled out the form wrong, fix these errors' before they have interacted with the form.

const [errors, setErrors] = useState([]);
const [ errorsHidden, setErrorsHidden ] = useState(true);

const handleSubmit = (e) => {
    setErrorsHidden(false)
    if(errors.length > 0){
        return
    }...
...

<div hidden={errorsHidden}>
   {errors.map((error, ind) => (
       <div className='cc-error' key={ind}>{error}</div>
   ))}
</div>

Clone this wiki locally