Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

339
Views
¿Cómo renderizo CSS condicionalmente con Material UI useStyles/makeStyles?

Estoy tratando de mostrar la variable LatestMessageText en negrita y negro si los accesorios cumplen con una determinada condición. El método useEffect funciona, una solución fea; ¿Cómo uso el gancho useStyle de Material UI para ejecutar mi objetivo? Intenté pasar accesorios a useStyle, usándolos dentro de la función makeStyles, sin ningún efecto.

 import React, { useEffect, useRef } from "react"; import { Box, Typography } from "@material-ui/core"; import { makeStyles } from "@material-ui/core/styles"; const useStyles = makeStyles((theme) => ({ root: { display: "flex", justifyContent: "space-between", marginLeft: 20, flexGrow: 1, }, username: { fontWeight: "bold", letterSpacing: -0.2, }, previewText: { fontSize: 12, // color: "#9CADC8", letterSpacing: -0.17, color: (messages, otherUser) => { if (messages.length && otherUser) { const lastMessage = messages[messages.length - 1]; const { senderId, receiverHasRead } = lastMessage; if (senderId === otherUser.id && !receiverHasRead) { return 'black' } return "#9CADC8" } } }, black: { color: 'black', fontWeight: 700, } })); const ChatContent = (props) => { const { conversation } = props; const { latestMessageText, otherUser, messages } = conversation; const classes = useStyles(messages, otherUser); return ( <Box className={classes.root}> <Box> <Typography className={classes.username}> {otherUser.username} </Typography> <Typography className={classes.previewText}> {latestMessageText} </Typography> </Box> </Box> ); }; export default ChatContent;
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Recomiendo aquí usar una utilidad pequeña (228B) para construir cadenas className condicionalmente, que es clsx .

Proporcioné una solución aquí.

Primer método con sintaxis {[yourclass]: conditon} :

 import React, { useEffect, useRef } from "react"; import { Box, Typography } from "@material-ui/core"; import { makeStyles } from "@material-ui/core/styles"; import clsx from 'clsx'; const useStyles = makeStyles((theme) => ({ root: { display: "flex", justifyContent: "space-between", marginLeft: 20, flexGrow: 1, }, username: { fontWeight: "bold", letterSpacing: -0.2, }, previewText: { fontSize: 12, color: "#9CADC8", letterSpacing: -0.17, }, black: { color: 'black', fontWeight: 700, } })); const ChatContent = (props) => { const classes = useStyles(); const typeographyEl = useRef(); const { conversation } = props; const { latestMessageText, otherUser, messages } = conversation; const lastMessage = messages?.length && messages[messages.length - 1]; const { senderId, receiverHasRead } = lastMessage; return ( <Box className={classes.root}> <Box> <Typography className={classes.username}> {otherUser.username} </Typography> <Typography ref={typeographyEl} className={clsx(classes.previewText, {[classes.black]: senderId === otherUser.id && !receiverHasRead})}> {latestMessageText} </Typography> </Box> </Box> ); }; export default ChatContent;

O segundo método con sintaxis {conditon && yourstyle} :

 <Typography ref={typeographyEl} className={clsx(classes.previewText, {(senderId === otherUser.id && !receiverHasRead) && classes.black})}> {latestMessageText} </Typography>
about 4 years ago · Juan Pablo Isaza Report

0

Esa no es la forma React de manejar este tipo de función. Debe obtener la condición en una variable de estado (si espera que cambie por la interacción del usuario) o una variable constante de lo contrario, y establecer la clase en función de eso.

 const [messageRead, setMessageRead] = useState(false); useEffect(() => { if (messages.length) { const { senderId, receiverHasRead } = messages[messages.length - 1]; setMessageRead(senderId === otherUser.id && !receiverHasRead); } }, [messages, otherUser]);

JSX

 <Typography className={`${classes.previewText} ${messageRead ? classes.black : ''}`}> {latestMessageText} </Typography>

Puede usar el paquete classnames o clsx npm para simplificar la condición ternaria.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!