const activeStyle = {
border: '1px solid transparent',
borderColor: '#e4e6e8',
borderBottomColor: '#fff',
marginBottom: '-1px',
cursor: 'default'
}
const notActive = {
cursor: 'pointer'
}
class LoginSignup extends React.Component {
render() {
const pathName = this.props.history.location.pathname;
return (
<div style={{ pathName === '/login' ? ...activeStyle : ...notActive }}>
<Link to='/login'><span>Log in</span></Link>
</div>
<div style={{ pathName === '/signup' ? ...activeStyle : ...notActive }}>
<Link to='/signup'><span>Sign up</span></Link>
</div>
</div>
);
}
}
export default withRouter(LoginSignup);
I want to apply different styles based on the location path name. How to do that? I tried ternary operator inside style attribute but it shows Unexpted token, expected , error.
You will need to write it like so:
<div style={pathName === '/login' ? activeStyle : notActive}>...</div>
If you need to concat some styles, I would do something along the lines:
<div style={pathName === '/login' ? activeStyle : { ...activeStyle, ...notActive}}>...</div>
For readability, maybe rename the activeStyle
to defaultStyle
.
you can try the code like below.
const pathName = this.props.history.location.pathname;
let headerlink='';
if(pathName=='/login'){
headerlink=<div style={{...activeStyle }}>
<Link to='/login'><span>Log in</span></Link>
</div>
}else{
headerlink=<div style={{...notActive }}>
<Link to='/signup'><span>Sign up</span></Link>
</div>;
}
return headerlink;
Your spread operator is incorrect you need to spread it within object. One of the following two approaches will work.
class LoginSignup extends React.Component {
render() {
const pathName = this.props.history.location.pathname;
return (
<div style={{ pathName === '/login' ? activeStyle : notActive }}>
<Link to='/login'><span>Log in</span></Link>
</div>
<div style={{ pathName === '/signup' ? activeStyle : notActive }}>
<Link to='/signup'><span>Sign up</span></Link>
</div>
</div>
);
}
}
OR
class LoginSignup extends React.Component {
render() {
const pathName = this.props.history.location.pathname;
return (
<div style={{ pathName === '/login' ? {...activeStyle} : {...notActive} }}>
<Link to='/login'><span>Log in</span></Link>
</div>
<div style={{ pathName === '/signup' ? {...activeStyle} : {...notActive} }}>
<Link to='/signup'><span>Sign up</span></Link>
</div>
</div>
);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.