I'm very new to Reactjs, and I have an td
in my render
method:
<td style={{cursor: 'pointer'}} onClick={} key={i}>
On click of this td
, I want to change its style, how one should do this in react js?
Thanks.
This is how I have generated by td
:
{this.props.posts.map((service, i) =>
<tr>
<td style={{cursor: 'pointer'}} key={i}>
<span> {posts.createdBy} </span>
</td>
</tr>
)}
For modern react:
You can change values from state
import { useState } from 'react';
const App = () => {
const [ color, setColor ] = useState('#fff');
const [ backgroundColor, setBackgroundColor ] = useState('#f44');
return (
<p style={{ 'color': color, 'backgroundColor': backgroundColor }} >
Hello world
</p>
);
};
export default App;
Or you can toggle between two values
import { useState } from 'react';
const App = () => {
const [ isFullWidth, setIsFullWidth ] = useState(false);
return (
<p style={{'width':` ${isFullWidth ? '100%' : '20%'}`}} >
Hello world
</p>
);
};
export default App;
Supposing of course that all the other ducks are in order, you can keep track of the class in the components state, and then update the state with logic in the onClick event.
var TableData = React.createClass({
getInitialState: function() {
return {
class: 'pointer'
};
},
changeStyle: function(e) {
if (this.state.class === 'pointer') {
this.setState({class: 'not pointer'});
} else {
this.setState({class: 'pointer'});
}
},
render: function() {
return (
<td style={ cursor: {this.state.class} }
onClick={this.changeStyle}
key={i}>
</td>
);
}
});
You can actually do this programmatically using React.createRef then use a function to change the element using referencedElement.style.someStyle = style.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With