Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the style of an element in React?

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.

Edited:

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>
)}
like image 624
karthick krishna Avatar asked Nov 08 '15 11:11

karthick krishna


3 Answers

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;


like image 146
shahul01 Avatar answered Oct 07 '22 03:10

shahul01


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>
    );
  }
});
like image 7
Jonah Williams Avatar answered Oct 07 '22 05:10

Jonah Williams


You can actually do this programmatically using React.createRef then use a function to change the element using referencedElement.style.someStyle = style.

like image 2
eqprog Avatar answered Oct 07 '22 05:10

eqprog