Si tiene problemas con el desafío Change Inline CSS Conditionally Based on Component State de freeCodeCamp, probablemente no esté solo.
En este desafío, debe agregar código para cambiar algunos CSS en línea condicionalmente según el estado de un componente de React.
Cuando vaya por primera vez al desafío, este es el código que verá:
class GateKeeper extends React.Component { constructor(props) { super(props); this.state = { input: '' }; this.handleChange = this.handleChange.bind(this); } handleChange(event) { this.setState({ input: event.target.value }) } render() { let inputStyle = { border: '1px solid black' }; // change code below this line // change code above this line return ( Don't Type Too Much:
); } };
Observe que un objeto de estilo en línea,, inputStyle
ya se ha declarado con un estilo predeterminado.
Su objetivo en este desafío es actualizar inputStyle
para que el borde de la entrada sea 3px solid red
cuando haya más de 15 caracteres en la entrada. Tenga en cuenta que el texto del cuadro de entrada se guarda en el estado del componente como input
:
... this.state = { input: '' }; ...
Cerca, pero no del todo
Imagina que, después de leer la descripción y las instrucciones, se te ocurre esto:
class GateKeeper extends React.Component { constructor(props) { super(props); this.state = { input: '' }; this.handleChange = this.handleChange.bind(this); } handleChange(event) { this.setState({ input: event.target.value }) } render() { let inputStyle = { border: '1px solid black' }; // change code below this line const char = 15; if(this.state.input > char) { inputStyle = { border:'3px solid red' } } // change code above this line return ( Don't Type Too Much:
); } };
Pero cuando intenta enviar esto, no pasa todas las pruebas. Echemos un vistazo más de cerca a lo que está pasando.
Soluciones
Usando una if
declaración
Declarar char
está bien, pero observe más de cerca la if
condición:
if(this.state.input > char) { inputStyle = { border:'3px solid red' } }
Recuerde que this.state.input
es el valor del cuadro de entrada y es una cadena. Por ejemplo, podría ser "prueba de prueba 1, 2, 3".
Si ingresa "testing testing 1, 2, 3" en el cuadro de texto y lote this.state.input
en la consola:
class GateKeeper extends React.Component { constructor(props) { super(props); this.state = { input: '' }; this.handleChange = this.handleChange.bind(this); } handleChange(event) { this.setState({ input: event.target.value }) } render() { let inputStyle = { border: '1px solid black' }; // change code below this line const char = 15; console.log(this.state.input); if(this.state.input > char) { inputStyle = { border:'3px solid red' } } // change code above this line return ( Don't Type Too Much:
); } };
Verás testing testing 1, 2, 3
en la consola.
Además, si inicia sesión this.state.input > char
en la consola, verá que se evalúa como false
:
class GateKeeper extends React.Component { constructor(props) { super(props); this.state = { input: '' }; this.handleChange = this.handleChange.bind(this); } handleChange(event) { this.setState({ input: event.target.value }) } render() { let inputStyle = { border: '1px solid black' }; // change code below this line const char = 15; console.log(this.state.input > char); if(this.state.input > char) { inputStyle = { border:'3px solid red' } } // change code above this line return ( Don't Type Too Much:
); } };
En pocas palabras, no puede comparar una cadena ( this.state.input
) directamente con char
, que es un número.
En su lugar, llame a .length
on this.state.input
para obtener la longitud de la cadena y compárela con count
:
class GateKeeper extends React.Component { constructor(props) { super(props); this.state = { input: '' }; this.handleChange = this.handleChange.bind(this); } handleChange(event) { this.setState({ input: event.target.value }) } render() { let inputStyle = { border: '1px solid black' }; // change code below this line const char = 15; if(this.state.input.length > char) { inputStyle = { border:'3px solid red' } } // change code above this line return ( Don't Type Too Much:
); } };
Dado que la longitud de la cadena "testing testing 1, 2, 3" tiene 23 caracteres (incluidos los espacios y las comas), el borde del cuadro de entrada se volverá rojo:

Usando un operador ternario
Un operador ternario o condicional es como una if...else
declaración de una línea y puede ayudar a acortar su código de manera significativa.
Regrese a su solución y elimine todo excepto la char
variable:
class GateKeeper extends React.Component { constructor(props) { super(props); this.state = { input: '' }; this.handleChange = this.handleChange.bind(this); } handleChange(event) { this.setState({ input: event.target.value }) } render() { let inputStyle = { border: '1px solid black' }; // change code below this line // change code above this line return ( Don't Type Too Much:
); } };
Ahora tome la condición que utilizó en su if
declaración anterior y úsela como la primera parte de la condición ternaria:this.state.input.length > char ? : ;
Todo entre ?
e :
indica lo que sucede si la declaración anterior es verdadera. Puede simplemente copiar el código que estaba dentro de su if
declaración antes:this.state.input.length > char ? inputStyle = { border:'3px solid red' } : ;
Ahora necesita manejar la else
parte del operador ternario, que es todo entre :
y ;
.
Si bien no usó una else
declaración en su primera solución, efectivamente la usó inputStyle
como está. Así que usa inputStyle
la forma en que se declaró anteriormente en tu código:this.state.input.length > char ? inputStyle = { border:'3px solid red' } : inputStyle;
Toda su solución debería verse así:
class GateKeeper extends React.Component { constructor(props) { super(props); this.state = { input: '' }; this.handleChange = this.handleChange.bind(this); } handleChange(event) { this.setState({ input: event.target.value }) } render() { let inputStyle = { border: '1px solid black' }; // change code below this line const char = 15; this.state.input.length > char ? inputStyle = { border:'3px solid red' } : inputStyle; // change code above this line return ( Don't Type Too Much:
); } };
Y eso es todo, ¡deberías poder aprobar el desafío! Ahora avanza y diseña condicionalmente los componentes de React a tu gusto.