How to Dynamically change the style of a react component
As your question asked, I tried to have a sample of making dynamic style
which depends, in my case, on the index of the array. Changing colors of the background made me come up with this solution:
App.js
import { Word } from "./word";
//import './typeTest.css'
export default function App() {
const test1 =
"the quick brown fox jumped over a tree and tripped over that tree the quick brown fox jumped over a tree and tripped over that tree the quick brown fox jumped over a tree and tripped over that tree the quick brown fox jumped over a tree and tripped over that tree";
const test1Arr = test1.split(" ");
return (
<div>
<div style={{display:"flex"}}>
{test1Arr.map((monoWord, index) => (
<Word
inputWord={monoWord}
style={{
background: `#${(index*2).toString(16)}${index.toString(16)}${((index+1)/2).toString(16)}`
}}
/>
))}
<Word inputWord="Scoll" />
</div>
</div>
);
}
word.js
export const Word = (props) => {
return <h1 style={props.style}>{props.inputWord}</h1>;
};
As you can see in the word.js
component we get the props of style, which is applied later to the child component. Passing the background is the most visible change in styles, so I implemented that. The same technique you would use if you implement a className
, which is conditionally writable as string. Here is the example in sandbox.
Change style of the text dynamically React js
You have to lift the active tab state from the Tab
component to the Header
one and set a callback that will be passed to the Tab
component, in order to update the state in the parent.
You should end up with something like:
const tabs = ['About', 'Portfolio', 'Blogs', 'Contact']
const Header = () => {
const [activeTab, setActiveTab] = useState('');
const handleTabClick = useCallback((tab) => {
setActiveTab(tab);
}, []);
return (
<div className="header">
{tabs.map((elem) => {
return <Tab key={elem} text={elem} isActive={elem === activeTab} onTabClick={handleTabClick} />;
})}
</div>
);
}
const Tab = ({ text, isActive, onTabClick }) => {
return (
<div className="tab">
<div
className={`text ${isActive && "active"}`}
onClick={() => onTabClick(text)}
>
{text}
</div>
</div>
);
}
setting style values dynamically - react
First of all, this is not the right approach while applying styles.
Solution 1:
If you are using plain css, you can keep your styles in separate css files.
For example,
.tradeWaterGrabSample {
// your styles
}
.hidden {
display: none;
}
Later, in JSX you can put the css classes:
For example
<Grid container spacing={3} className=`tradeWaterGrabSample ${yourCondition ? 'hidden' : ''}`>
</Grid>
Solution 2:
You can use classnames / clsx npm library for applying multiple styles:
https://www.npmjs.com/package/clsx
https://www.npmjs.com/package/classnames
in this case you can easily apply multiple classes based on condition:
Eg:
import classNames from 'classnames';
...
<Grid container spacing={3} className={classNames('tradeWaterGrabSample' , {'hidden': true}> // replace true by your condition
</Grid>
Solution 3:
By seeing Grid container
I am assuming you are using material-ui / MUI.
If your using MUI (Aka v5), then you can use sx prop
For example,
<Grid container spacing={3} sx={{
display: condition ? 'none' : 'flex'
}}
justifyContent="center"
mt="5px"
>
</Grid>
For reference:
https://mui.com/system/the-sx-prop
https://mui.com/guides/interoperability/
If your using Material ui (Aka v4), then "sx" prop does not work. you can use makeStyles / withStyles instead.
References:
https://v4.mui.com/styles/api/
https://v4.mui.com/guides/interoperability/
As you confirmed about material-ui v4
You can use following:
const useStyles = makeStyles({
gridContainer: {
marginTop: "5px"
},
hidden: {
display: "none"
},
});
use following inside component:
const classes = useStyles(props);
<Grid
container
spacing={3}
justifyContent="center"
className={classNames(classes.gridContainer, { [classes.hidden]: true } )} // replace true by your condition
>
</Grid>
https://v4.mui.com/styles/api/#makestyles-styles-options-hook
Based on your comment, to use component's props, you can follow this example:
https://v4.mui.com/styles/basics/#adapting-based-on-props
How to dynamically change styling of a dynamic piece in react (using functional components)?
So this would be how I would do it. I abstracted Square to be its own component and it is being create via your for loop. Each of these Squares can manage their own local state so when they are clicked they can update their own state and you dont need to have messy centralized code.
FYI you seem to be using useState
incorrectly as it does have its own function to update its local state. The below code is not 100% correct as Im not sure what you are doing, but it should give you a general outline.
I would also review the React docs: https://reactjs.org/docs/hooks-state.html
Just so you can get clear about the useState
hook and how it can be utilized.
const { useState } from 'react'
const Square = (i, j, data, count, isMove, selectMove) => {
const [ squareStyle, setSquareStyle ] = useState('square') // then use setSquareStyle('STYLING) to update local state
const selectedPiece = data[count].name
return (
<div key={count}
id={i * 10 + j}
className={getClassName(i, j)}
onClick={isMove ? selectMove : selectedPiece ? selectPiece : undefined }>
{ (selectedPiece.name != null) &&
<img src={images[props.data[count].name]}
className="icons"
alt="chess piece" />
}
</div>
)
}
function Row(i){
const newRow = [];
let count = i * 8;
for (let j = 0; j<8; j++){
newRow.push(
<Square
i={i}
j={j}
count={count}
isMove={isMove}
selectMove={selectMove}
/>
)
count++;
}
return <div className="rows" key={i}>{newRow}</div>;
}
//function getClassName(e, i, j){ //can't read e
function getClassName(i, j){
console.log(i, j)
//console.log(e.currentTarget)
let base = "squares ";
if (clicked){
// if (clicked && e.currentTarget.id == i * 10 + j){ //this is what I want but I can't figure out how to grab the target to compared the id to
return base + "b";
} else {
if ((i + j) % 2 === 1){
return base + "g";
}else {
return base + "y";
}
}
}
How do I dynamically add styles to a React style attribute?
You can use the object spread operator - this works well with style objects composition:
style={{
...field.currency ? {
paddingLeft: '10px',
} : {},
...field.name === 'makePrimary' ? {
color: 'grey',
background: 'blue'
} : {}
}}
How can I dynamically change the value of a CSS property in React?
Directly you can pass to html tag as an object style like this
<div className="background"
style={{ opacity: this.props.opacity }}
/>
React native - Change styles dynamically
You can add a style
prop to TouchableOpacity
and check if this is the selected button like this:
<TouchableOpacity
style={{ borderBottomWidth: this.state.selected === option.code ? 1 : 0 }}
onPress={() => this.setState({ selected: option.code })
>
...
</TouchableOpacity>
Also I guess you can use this.procedureOptionSelected()
since you set that option.code
in there too!
Related Topics
How to Get All the Applied Styles of an Element by Just Giving Its Id
JSON.Stringify Output to Div in Pretty Print Way
How to Get Color Value from Gradient by Percentage with JavaScript
Get Element Stylesheet Style in JavaScript
Inherited CSS Values via JavaScript
Ruby on Rails - Put Method on Update Ajax
Cors - How Do 'Preflight' an Httprequest
Chrome Extension Code VS Content Scripts VS Injected Scripts
How to Detect the Clearing of a "Search" HTML5 Input
How to Select All Text in Contenteditable Div
Convert JavaScript-Generated Svg to a File
How to Setup Less Using Only Js
Getting the Values of All the CSS Properties of a Selected Element in Selenium