karthick krishna
karthick krishna

Reputation: 151

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>
)}

Upvotes: 15

Views: 108218

Answers (6)

shahul01
shahul01

Reputation: 349

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;


Upvotes: 5

eqprog
eqprog

Reputation: 106

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

Upvotes: 3

thuva4
thuva4

Reputation: 1225

Don't use the inline styles, inline styles are too expensive. Use default .css.

table.css : Maintain two classes

.td {cursor: 'pointer'}

.td-clicked {
 //your classAtributes
}

index.js: Maintain the unique key for each td. If the user clicked the one td use the onClick listener to change the class of that particular td.

import React, { useState } from "react";
import './table.css';
const Table = () => {
  const [clickTd, setClickedTd] = useState(null);
  return (
    <>
      {this.props.posts.map((service, i) => {
        return (
          <tr>
            <td
              className={clickId == i ? "td-clicked" : "id"}
              key={i}
              onClick={() => setClickId(i)}
            >
              <span> {posts.createdBy} </span>
            </td>
          </tr>
        );
      })}
      )}
    </>
  );
};

Upvotes: 1

dabeng
dabeng

Reputation: 1450

@karthick krishna .I create a demo according to your question. td will be selected on user clicks the date column of Post List.

class PostList extends React.Component {
  constructor() {
    super();
    this.state = { selectedPost: {} };
  }
  render() {
    return (
      <table>
        {this.props.posts.map(post => (
          <tr key={post.id}>
            <td>{post.title}</td>
            <td
              className={
                this.state.selectedPost.id === post.id ? "selected" : ""
              }
              onClick={this.selectPost.bind(this, post)}
              style={{ cursor: "pointer" }}
            >
              <span>{post.createdBy}</span>
            </td>
          </tr>
        ))}
      </table>
    );
  }

  selectPost(selected) {
    if (selected.id !== this.state.selectedPost.id) {
      this.setState({ selectedPost: selected });
    } else {
      this.setState({ selectedPost: {} });
    }
  }
}

const postData = [
  { id: "1", title: "jQuery is great", createdBy: "2019-01-15" },
  { id: "2", title: "ES6 is cool", createdBy: "2019-02-15" },
  { id: "3", title: "Vuejs is awesome", createdBy: "2019-03-15" }
];
const element = (
  <div>
    <h1>Post List</h1>
    <PostList posts={postData} />
  </div>
);
ReactDOM.render(element, document.getElementById("root"));
.selected {
  background-color: rgba(217, 83, 79, 0.8);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="root"></div>

Upvotes: 0

reuvenaor
reuvenaor

Reputation: 1

You can easily inject the inline style updated state or any CSS object representative.

Combine it with with static CSS class (ClassName in the expamle).

    constructor(props) {
    super(props);
    this.filters = {filter: 'blur(5px)'};
    this.state = {
        filters: {filter: 'blur(5px)'}
    };
}

CSS object injected with any trigger you choose:

<img src="/static/back.jpg" className={'background'} style={this.filters}></img>

Or with updated state triggered with setState():

<img src="/static/back.jpg" className={'background'} style={this.state.filters}></img

Upvotes: 0

Jonah Williams
Jonah Williams

Reputation: 21441

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>
    );
  }
});

Upvotes: 7

Related Questions