0

I made a variable that has the style which I would want the input box to change to when it is clicked on. How can I implement it so that when the input box is clicked, the border color of the input box changes to blue, considering that CSS, styles and everything else are imported?

    const inputStyle = css
      border-color: blue;
    ;      

    const InputBox = styled.input
      myClick: function () {
      inputstyle
      }
   ;

    render() {
    return (
        <InputBox
          placeholder='Click Me'
          type='text'
          onClick={this.myClick}
        />

3 Answers 3

1

styled.foo doesn't return a class component, so writing methods as if they're on a class in the template string won't work.

Since you're handling something stateful (was this thing clicked?) you need to have some place to put that state. Then you can pass that state to the InputBox component:

const InputBox = styled.input`
  border-color: ${({ clicked }) => clicked ? 'blue' : 'transparent'};
`

class Parent extends React.Component {
  constructor (props) {
    this.state = { clicked: false }
  }
  handleClick () {
    this.setState({ clicked: true })
  }
  render () {
    return (
      <InputBox
        placeholder="Click Me"
        type="text"
        clicked={this.state.clicked}
        onClick={this.handleClick}
      />
    )
  }
}

I'd suggest checking out the "Passed Props" section of the styled-components docs.

Sign up to request clarification or add additional context in comments.

Comments

1

you can do this :

const Styles = {
inputNormal:{color:'blue'},
inputClicked:{color:'red'}
}
class Parent extends React.Component {
constructor (props) {
this.state = { clicked: false }
}
handleClick () {
this.setState({ clicked: true })
}

render () {
  return (
    <InputBox
      placeholder="Click Me"
      type="text"
      style={this.state.clicked?styles.inputNormal:styles.inputClicked}
      onClick={this.handleClick}
    />
  )}}

Comments

0

You should add styles with variables like this:

class App extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      clicked: false
    };
  }

  myClick = () => {
    this.setState({
      clicked: true
    });
  };

  render() {
    const inputStyle = {
      borderColor: "blue"
    };

    return (
      <input
        placeholder="Click Me"
        type="text"
        onClick={this.myClick}
        style={this.state.clicked ? inputStyle : null}
      />
    );
  }
}

Here is a working demo:

DEMO

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.